publicstaticvoidinsertSort(int array[], int left, int right){ for (int i = left + 1; i <= right; i++) { int temp = array[i];//保存当前的值 int j = i - 1; while (j >= left && array[j] > temp) { array[j + 1] = array[j]; j--; } //也可以改写成下面这种形式 /* while (j>=left){ if (array[j]<=temp) break; array[j+1]=array[j]; j--; } */ array[j + 1] = temp; } }
publicstaticvoidquickSort(int array[], int left, int right){ if (left >= right)//如果左边界大于右边界,则停止递归 return; int i = left, j = right;//获取左右边界 int temp = array[i];//取序列第一个值为参考值 while (i < j) { while (i < j && array[j] >= temp) { j--; } array[i] = array[j]; while (i < j && array[i] <= temp) { i++; } array[j] = array[i]; } array[i] = temp; quickSort(array, left, i - 1);//递归左边 quickSort(array, i + 1, right);//递归右边 }
publicstaticvoidsplitArray(int array[], int left, int right){ //拆分 if (left >= right) return; int mid = (left + right) / 2; splitArray(array, left, mid);//递归拆分左边 splitArray(array, mid + 1, right);//递归拆分右边 mergeArray(array, left, mid, right);//实现归并 }
publicstaticvoidmergeArray(int array[], int left, int mid, int right){ //归并 if (left > right) return; int i = left, j = mid + 1;//设置两个起始点 int index=0;//新数组的下标 int temp[]=newint[right-left+1];//新建一个数组,保存数据 while (i<=mid&&j<=right){//把较小的数存入数组 if (array[i] temp[index++]=array[i++]; }else{ temp[index++]=array[j++]; } } while (i<=mid){//把左数组放入新数组 temp[index++]=array[i++]; } while (j<=right){//把右数组放入新数组 temp[index++]=array[j++]; } //将新数组覆盖掉旧数组 index=0; while (left<=right){ array[left++]=temp[index++]; } }
publicstaticvoidbinaryInsertSort(int array[], int left, int right){ for (int i=left+1;i<=right;i++){ int low=left,high=i-1; while(low<=high){//利用二分法找到要插入的地方 int mid=(high+low)/2; if (array[mid]>array[i]){ high=mid-1; }else{ low=mid+1; } } int temp=array[i]; for (int j=i;j>high+1;j--){ array[j]=array[j-1]; } array[high+1]=temp; } }
publicstaticvoidcocktailSort(int array[], int left, int right){ int low=left,high=right;//初始化边界 while (low for (int i=low;i if (array[i]>array[i+1]){ int cont=array[i]; array[i]=array[i+1]; array[i+1]=cont; } } high--; for (int i=high;i>low;i--){ if (array[i]1]){ int cont=array[i]; array[i]=array[i-1]; array[i-1]=cont; } } low++; } }