这是我在Java上的快速排序代码。我已经为3种不同类型的列表尝试了这个代码;
它只适用于排序列表,但是对于排序列表,它会打印出来;
1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47 ,49,51,53,55,57,59,61,63,65,67,66,68,64,69,62,70,60,71,58,72,56,73,54,74,52 ,75,50,76,48,77,46,78,44,79,42,80,40,81,38,82,36,83,34,84,32,85,30,86,28,87 ,26,88,24,89,22,90,20,91,18,92,16,93,14,94,12,95,10,96,8,97,6,98,4,99,2 ,100
对于随机列表,它会改变。
我无法解决这个问题,任何人都可以帮忙吗? 提前谢谢。
class QuickSort {
public int Partition(int[] numbers, int left, int right){
int pivot = numbers[left];
while (true)
{
while (numbers[left] < pivot)
left++;
while (numbers[right] > pivot)
right--;
if (left < right)
{
int temp = numbers[right];
numbers[right] = numbers[left];
numbers[left] = temp;
left++;
right--;
}
else
{
return right;
}
}
}
public void QuickSort(int[] arr, int left, int right){
// For Recusrion
if(left < right)
{
int pivot = Partition(arr, left, right);
if(pivot > 1)
QuickSort(arr, left, pivot - 1);
if(pivot + 1 < right)
QuickSort(arr, pivot + 1, right);
}
}
////////////////////////////////////////////////////////////
public void printArray(int[] arr){
for (int i = 0; i < arr.length; i++){
if (i==arr.length-1)
System.out.print(arr[i]);
else
System.out.print(arr[i]+", ");
}
System.out.println();
}
public int[] fillArraySorted(int len){
int[] result=new int[len];
int counter = 1;
for(int i=0; i<len; i++){
result[i]=counter;
counter++;
}
return result;
}
public int[] fillArrayRan(int len){
int[] result=new int[len];
Random r = new Random();
for(int i=0; i<len; i++){
result[i]=r.nextInt(100)+1;
}
return result;
}
public int[] fillArraySortedReversed(int len){
int[] result=new int[len];
int counter = len;
for(int i=0; i<len; i++){
result[i]=counter;
counter--;
}
return result;
}
}
}