发布网友 发布时间:2022-04-24 11:18
共2个回答
热心网友 时间:2023-10-11 00:16
java:
Java排序算法
package com.cucu.test;
/**
* @author http://www.linewell.com <a href=mailto:cg@linewell.com>cg@linewell.com</a>
* @version 1.0
*/
public class Sort {
public void swap(int a[], int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public int partition(int a[], int low, int high) {
int pivot, p_pos, i;
p_pos = low;
pivot = a[p_pos];
for (i = low + 1; i <= high; i++) {
if (a[i] > pivot) {
p_pos++;
swap(a, p_pos, i);
}
}
swap(a, low, p_pos);
return p_pos;
}
public void quicksort(int a[], int low, int high) {
int pivot;
if (low < high) {
pivot = partition(a, low, high);
quicksort(a, low, pivot - 1);
quicksort(a, pivot + 1, high);
}
}
public static void main(String args[]) {
int vec[] = new int[] { 37, 47, 23, -5, 19, 56 };
int temp;
//选择排序法(Selection Sort)
long begin = System.currentTimeMillis();
for (int k = 0; k < 1000000; k++) {
for (int i = 0; i < vec.length; i++) {
for (int j = i; j < vec.length; j++) {
if (vec[j] > vec[i]) {
temp = vec[i];
vec[i] = vec[j];
vec[j] = temp;
}
}
}
}
long end = System.currentTimeMillis();
System.out.println("选择法用时为:" + (end - begin));
//打印排序好的结果
for (int i = 0; i < vec.length; i++) {
System.out.println(vec[i]);
}
// 冒泡排序法(Bubble Sort)
begin = System.currentTimeMillis();
for (int k = 0; k < 1000000; k++) {
for (int i = 0; i < vec.length; i++) {
for (int j = i; j < vec.length - 1; j++) {
if (vec[j + 1] > vec[j]) {
temp = vec[j + 1];
vec[j + 1] = vec[j];
vec[j] = temp;
}
}
}
}
end = System.currentTimeMillis();
System.out.println("冒泡法用时为:" + (end - begin));
//打印排序好的结果
for (int i = 0; i < vec.length; i++) {
System.out.println(vec[i]);
}
//插入排序法(Insertion Sort)
begin = System.currentTimeMillis();
for (int k = 0; k < 1000000; k++) {
for (int i = 1; i < vec.length; i++) {
int j = i;
while (vec[j - 1] < vec[i]) {
vec[j] = vec[j - 1];
j--;
if (j <= 0) {
break;
}
}
vec[j] = vec[i];
}
}
end = System.currentTimeMillis();
System.out.println("插入法用时为:" + (end - begin));
//打印排序好的结果
for (int i = 0; i < vec.length; i++) {
System.out.println(vec[i]);
}
//快速排序法(Quick Sort)
Sort s = new Sort();
begin = System.currentTimeMillis();
for (int k = 0; k < 1000000; k++) {
s.quicksort(vec, 0, 5);
}
end = System.currentTimeMillis();
System.out.println("快速法用时为:" + (end - begin));
//打印排序好的结果
for (int i = 0; i < vec.length; i++) {
System.out.println(vec[i]);
}
}
}
以下是运行结果:
选择法用时为:234
56
47
37
23
19
-5
冒泡法用时为:172
56
47
37
23
19
-5
插入法用时为:78
56
47
37
23
19
-5
快速法用时为:297
56
47
37
23
19
-5
热心网友 时间:2023-10-11 00:17
顺序查找
折半查找
分块查找
直接查找
插入排序
希尔排序
选择排序
快速排序
希尔排序代码
*p=数组指针; n=数组元素个数
void Hill_arrangement(int *p,int n)
{int i,gap,j,temp;
gap=n/2;
while(gap>=1)
{for(i=gap;i<n;i++)
{temp=*(p+i);
j=i;
while(j>=gap&&*(p+j-gap)>temp)
{*(p+j)=*(p+j-gap);
j=j-gap;
*(p+j)=temp;
}
}
gap=gap/2;
}
}
有序表折半搜索代码(返回下标)
int binarysearch(int *p,int n,int k)
{int low=0,up=n-1,mid;
while(low<=up)
{mid=(low+up)/2;
if(k==*(p+mid))return mid;
else if(k<*(p+mid))up=mid-1;
else low=mid+1;
}
return -1;
}