首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

简单总结上各种排序算法

2012-08-30 
简单总结下各种排序算法public static void bubbleSort(int[] c){for(int i0,lenc.lengthileni++){fo

简单总结下各种排序算法

public static void bubbleSort(int[] c){for(int i=0,len=c.length;i<len;i++){for(int j=0;j<len-i-1;j++){if(c[j]>c[j+1]){Helper.swap(c, j+1, j);}}}}public static void selectionSort(int[] c){for(int i=0,len=c.length;i<len;i++){int k=i;for(int j=i+1;j<len;j++){if(c[j]<c[k])k=j;}if(k!=i){Helper.swap(c, i, k);}}}public static void insertionSort(int[] a){for(int i=1,len=a.length;i<len;i++){int j=i;while(j>0){if(a[j]<a[j-1]){Helper.swap(a,j,j-1);}j--;}}}public static void quickSort2(int[] c,int begin,int end){if(begin>end)return;int point=c[begin];int i=begin,j=end;int index=i;while(i<j){while(c[i]<point&&i<j)i++;if(i<j){c[index]=c[i];index=i;}while(c[j]>point&&i<j)j--;if(i<j){c[index]=c[j];index=j;}}c[index]=point;quickSort2(c,begin,i-1);quickSort2(c,i+1,end);}public static void quickSort(int[] c,int begin,int end){if(begin>end)return;int low=begin;int high=end;boolean flag=true;while(low!=high){if(c[low]>c[high]){Helper.swap(c, low, high);flag=!flag;}if(flag){high--;}else{low++;}}quickSort(c,begin,low-1);quickSort(c,high+1,end);}public static void heapsort(int[] c){int lastIndex=c.length-1;int rootIndex=(c.length/2)+1;for(int i=rootIndex;i>=0;i--){reheap(c,i,lastIndex);}Helper.swap(c, 0, lastIndex);for(int i=lastIndex-1;i>=0;i--){reheap(c,0,i);Helper.swap(c, 0,i);}}       //max-heappublic static void reheap(int[] heap,int rootIndex,int lastIndex){int orphan=heap[rootIndex];int leftIndex=rootIndex*2+1;boolean done=false;while(!done&&leftIndex<=lastIndex){int largeIndex=leftIndex;int rightIndex=leftIndex+1;if(rightIndex<=lastIndex&&heap[rightIndex]>heap[leftIndex]){largeIndex=rightIndex;}if(heap[largeIndex]>orphan){heap[rootIndex]=heap[largeIndex];rootIndex=largeIndex;leftIndex=rootIndex*2+1;}else{done=true;}}heap[rootIndex]=orphan;}public static void mergeSort(int[] c,int low,int high,int[] tmp){if(low>=high)return;int mid=(high&low)+((high^low)>>1);mergeSort(c,low,mid,tmp);mergeSort(c,mid+1,high,tmp);merge(c,low,mid,high,tmp);}public static void merge(int[] c,int low,int mid,int high,int[] tmp){int begin01=low;int end01=mid;int begin02=mid+1;int end02=high;int k=0;while(begin01<=end01&&begin02<=end02){if(c[begin01]<c[begin02]){tmp[k]=c[begin01];k++;begin01++;}else{tmp[k]=c[begin02];k++;begin02++;}}while(begin01<=end01){tmp[k++]=c[begin01++];}while(begin02<=end02){tmp[k++]=c[begin02++];}System.arraycopy(tmp, 0,  c,low, k);}
1 楼 pywepe 2012-02-05   备忘,,希望没有错误 2 楼 neyshule 2012-06-27   quicksort2是不是有问题,c[i]<=point? 3 楼 bylijinnan 昨天   neyshule 写道quicksort2是不是有问题,c[i]<=point?
嗯 我当时没考虑有相等的情况

热点排行