排序的每次迭代都假设减少可排序范围。基本上,它是一种分而治之的算法。
pivot
找到您指定范围的“中”点
问题是,你正在随机化pivot
,所以每次你运行排序时,它都会比较一些随机部分,可能包括你已经排序的一些部分......
所以,而不是使用...
int pivot = r.nextInt(high-low+1)+low;
你应该用...
int pivot = low + (high - low) / 2;
例如...
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class QuickSort {
static String[] strings;
public static void main(String[] args) {
List<String> values = new ArrayList<>(26);
for (int index = 0; index < 26; index++) {
values.add(new String(new char[]{(char)(65 + index)}));
}
Collections.shuffle(values);
strings = values.toArray(new String[values.size()]);
System.out.println("Before");
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i] + " ");
}
System.out.println("");
qsort(0, strings.length - 1);
System.out.println("The array, quicksorted: ");
for (int i = 0; i < strings.length; i++) {
System.out.print(strings[i] + " ");
}
System.out.println("\n");
}
static void qsort(int low, int high) {
int i = low, j = high;
// Get the pivot element
int pivot = low + (high - low) / 2;
String value = strings[pivot];
// Divide into two lists
while (i <= j) {
while (strings[i].compareTo(value) < 0) {
i++;
}
while (strings[j].compareTo(value) > 0) {
j--;
}
if (i <= j) {
exchange(i, j);
i++;
j--;
}
}
// Recursion
if (low < j) {
qsort(low, j);
}
if (i < high) {
qsort(i, high);
}
}
static void exchange(int i, int j) {
String temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
}
哪个产生...
Before
N S B A F Z X J Q K V C L R W E H Y M U G I D P T O
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
G U P Q D A W T R M E O X J S C I V Y F H L B N Z K
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
D Z C B Q O K W X F V G R S A U P T H Y I E N L M J
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
Q K H B W N J V C Y U O R P G I F D Z E L S A X M T
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
R V P G E S C A H W X I T D Z B K Q F M U Y L J N O
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
L O T E U D H N P J V I Q C X S Z W A R F K G Y B M
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
I E J F U X P K R Q L S C O Y W G A Z B V M D H N T
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
X L K T W E V J N Y G H O Q I M C P A R B F S U Z D
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
U X N T K Q S V P F W C G Y O L A B E H J R D M Z I
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Before
A J Z C M Y O Q F L K D P S X W N T I B H E R U V G
The array, quicksorted:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
nb-不要强调使用List
,我只是生成了一些随机String
的s;)