算法来源:
1.C语言:啊哈算法
2.Java:漫画算法:小灰的算法之旅
C语言实现
#include<stdio.h>
int a[100],n;
void quicksort(int left,int right)
{
int i,j;
int t;
int temp;
if(left>right){
return ;
}
temp = a[left];
i=left;
j=right;
while (i != j)
{
while(a[j] >= temp && i<j){
j--;
}
while(a[i] <= temp && i<j){
i++;
}
if(i<j){
t=a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];
a[i] = temp;
quicksort(left,i-1);
quicksort(i+1,right);
}
int main()
{
int i,j,t;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
quicksort(1,n);
for(i=1;i<=n;i++)
printf("%d ",a[i]);
return 0;
}
Java实现
public static void quickSort(int[] arr, int startIndex,
int endIndex) {
if (startIndex >= endIndex) {
return;
}
int pivotIndex = partition(arr, startIndex, endIndex);
quickSort(arr, startIndex, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, endIndex);
}
private static int partition(int[] arr, int startIndex,
int endIndex) {
int pivot = arr[startIndex];
int left = startIndex;
int right = endIndex;
while( left != right) {
while(left<right && arr[right] > pivot){
right--;
}
while( left<right && arr[left] <= pivot) {
left++;
}
if(left<right) {
int p = arr[left];
arr[left] = arr[right];
arr[right] = p;
}
}
arr[startIndex] = arr[left];
arr[left] = pivot;
return left;
}
public static void main(String[] args) {
int[] arr = new int[] {4,4,6,5,3,2,8,1};
quickSort(arr, 0, arr.length-1);
System.out.println(Arrays.toString(arr));
}