您好,登錄后才能下訂單哦!
快排的邏輯其實很簡單,
代碼如下:
public static void quickSort(int[] array) {
//待排序區間為[0, array.length - 1]
quickSortIternal(array, 0, array.length - 1);
}
private static void quickSortIternal(int[] array, int left, int right) {
if(left >= right)
return;
//這里的就選擇最左邊的元素作為基準值來操作
//index表示基準值停留的下標
int index = partition(array, left, right);
quickSortIternal(array, left, index - 1);
quickSortIternal(array, index + 1, right);
}
代碼如下:
public static void quickSort2(int[] array) {
Stack<Integer> stack = new Stack<>();
stack.push(array.length - 1);
stack.push(0);
while(!stack.isEmpty()) {
int left = stack.pop();
int right = stack.pop();
if(left >= right) {
continue;
}
int index = partition(array, left, right);
stack.push(right);
stack.push(index + 1);
stack.push(index - 1);
stack.push(left);
}
}
重點是partition的實現
代碼如下:
public int partition(int[] array, int left, int right) {
int pivot = array[left];
int l = left;
int r = right;
while(l < r) {
while(l < r && array[r] >= pivot) {
r--;
}
while(l < r && array[l] <= pivot) {
l++;
}
swap(array, l, r);
}
swap(array, left, l);
return l;
}
private static void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
代碼如下:
public int partition(int[] array, int left, int right) {
int pivot = array[left];
int l = left;
int r = right;
while(l < r) {
while(l < r && array[r] >= pivot) {
r--;
}
array[l] = array[r];
while(l < r && array[l] <= pivot) {
l++;
}
array[r] = array[l];
}
array[l] = pivot;
return l;
}
代碼如下:
private int partition(int[] array, int left, int right) {
int pivot = array[left];
int slow = left + 1;
int fast = left + 1;
while(fast <= right) {
if(array[fast] < pivot) {
swap(array, slow, fast);
slow++;
}
fast++;
}
swap(array, left, slow - 1);
return slow - 1;
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。