Java: sort
作者:互联网
选择排序:
protected static void selectSort(int[] array){ int tmp; int minIndex; for(int i = 0; i < array.length - 1; i++){ minIndex = i; for(int j = i + 1; j < array.length; j++){ if(array[j] < array[minIndex]){ minIndex = j; } } if(minIndex != i){ tmp = array[minIndex]; array[minIndex] = array[i]; array[i] = tmp; } } }
插入排序:
protected static void insertSort(int[] array){ int tmp; for(int i = 1; i < array.length; i++){ tmp = array[i]; int j = i - 1; // 有序区最大索引 while(j >= 0){ if(array[j] > tmp){ array[j + 1] = array[j]; }else{ // array[j + 1] = tmp; // 不能在此处, tmp为最小值时, 不会执行 // System.out.printf("\033[37;7m %s -- %s \033[0m\n", j + 1, tmp); break; } j--; } array[j + 1] = tmp; // j + 1 // System.out.println("\033[37;7m>>>>>> " + Arrays.toString(array) + " <<<<<<\033[0m"); } }
单边快排
private static void quickSort(int[] array, int low, int high){ if(low > high){ // low==high: 分区只有一个值, low>high: pivot为分区极小值, pivot为分区极大值: 此时右分区low为high+1, 不满足条件 return; } int base = partition(array, low, high); quickSort(array, low, base - 1); // 左分区 quickSort(array, base + 1, high); // 右分区 } private static int partition(int[] array, int low, int high){ int pivot = array[high]; int base = low; int tmp; for(int cursor = base; cursor < high; cursor++){ // base左边的值小于pivot if(array[cursor] < pivot){ if(cursor != base){ tmp = array[cursor]; array[cursor] = array[base]; array[base] = tmp; } base++; // base右移 } } if(base != high && array[base] != array[high]){ // base==high, pivot为分区最大值 tmp = array[base]; array[base] = pivot; array[high] = tmp; } return base; }
双边快排
private static void doubleQuickSort(int[] array, int low, int high){ // System.out.printf("\033[37;7m low: %d, high: %d \033[0m\n", low, high); if(low >= high) return; int partition = partition(array, low, high); doubleQuickSort(array, low, partition - 1); doubleQuickSort(array, partition + 1, high); } private static int partition(int[] array, int low, int high){ int pivot = array[low]; int lowCursor = low + 1; int highCursor = high; int tmp; while(lowCursor < highCursor){ while(pivot < array[highCursor]){ highCursor--; } while(lowCursor < highCursor && array[lowCursor] <= pivot){ lowCursor++; } if(lowCursor == highCursor){ System.out.printf("\033[37;7m Cursor: %d, lowCursor == highCursor \033[0m\n", lowCursor); break; }else{ tmp = array[lowCursor]; array[lowCursor] = array[highCursor]; array[highCursor] = tmp; } } tmp = array[highCursor]; array[highCursor] = pivot; array[low] = tmp; return lowCursor; }
标签:sort,tmp,Java,int,high,base,low,array 来源: https://www.cnblogs.com/dissipate/p/16343855.html