C语言版本(借鉴其他博客)
#include<stdio.h>
int partition(int pArr[], int low, int high)
{
int pivot = pArr[low];
while (low < high)
{
while (low<high&&pArr[high] >= pivot) high--;
pArr[low] = pArr[high];
while (low<high&&pArr[low] <= pivot) low++;
pArr[high] = pArr[low];
}
pArr[low] = pivot;
return low;
}
void Quick_sort(int pArr[], int low, int high)
{
int keyPos = 0;
if (low<high)
{
keyPos = partition(pArr, low, high);
Quick_sort(pArr, low, keyPos - 1);
Quick_sort(pArr, keyPos + 1, high);
}
}
int main(int argc, char**argv)
{
//int arr[] = { 49,38,65,97,76,13,27,49 };
int arr[] = { 32,34,65,9,76,13,27,49 };
/*注意size-1*/
Quick_sort(arr, 0, sizeof(arr) / sizeof(arr[0]) - 1);
for (int i = 0; i<sizeof(arr) / sizeof(arr[0]); i++)
{
printf("%2d ", arr[i]);
}
getchar();
return 0;
}
运行结果:
Java
public class Qsort {
private static int partition(int[] arr,int low,int high) {
int t = arr[low];
while(low<high) {
while(low<high && arr[high]>=t)
high--;
arr[low]=arr[high];
while(low<high && arr[low]<=t)
low++;
arr[high]=arr[low];
}
arr[low]=t;
return low;
}
public static void qsort(int[] arr,int low,int high) {
int part=0;
if (low<high) {
part=partition(arr,low,high);
qsort(arr,low,part-1);
qsort(arr,part+1,high);
}
}
public static void main(String[] args) {
int[] arr= {32,34,65,9,76,13,27,49};
qsort(arr,0,arr.length-1);
for(int i=0;i<arr.length;i++) {
System.out.println(arr[i]);
}
}
}
运行结果:
如果你有疑惑,请与我联系chl.ai@outlook.com