快速排序的思想百度百科中有给出:http://baike.baidu.com/link?url=psrFy8x4mISy5ceWzM0L3VJeY0v9ZDhkSgOL5XIpXmc8R3RyxIZrF8ufbSMqedldyVkljHTKP0KU2iiWGluUNtQzhtgFV2wTzqNguLvvUUeS6e8F6yrYbkjvDbmZwDpQxlVf1VWLnAHqspF7Kg0MQTFHGMItb2mVWraEpBMcdCUgp5U3aJ3gKMhEDhl3LQEKRI7YqbtULL3zjh03EEmzoNMXZeO0AZJov1cLLjJunhI05PnfDvgyz5EO9zztXoWc,这边编写算法的时候,主要是纠结在如何根据一个指定的值分开数组。
#include<stdio.h>
#include<stdlib.h>
void sort(int arr[], int len);
//print the int array
void printArray(int arr[], int len);
//swap two value in one array
void swap(int[], int i, int j);
int main()
{
int data[] = {3,2,4,6,7,9,1,8,10,5};//,7,9,2,6,1,8,10};
sort(data, 10);
printArray(data, 10);
}
/*
say something about the quick sort,
first, you find the middle value, and
now, you want to keep the samll value to left,
and keep bigger value to right.
so, what would you do, how can you just put the
small value to left and bigger value to right.
you can just recode the index of samll value and
index of bigger value.
and then swap them.
*/
void sort(int arr[], int len)
{
if(len == 0)
{
return;
}
int temp = arr[0];
int i, j;
int mid = 0;
i = 0;
j = len - 1;
//include the length is 0 and 1
if(i >= j) return;
while(i < j)
{
while(temp < arr[j] && i < j)
{
j--;
//find the swap location
}
//chang the value
if(j == i) break;
swap(arr, i, j);
mid = j;
while(temp > arr[i] && i < j)
{
i++;
//find the bigger number
}
if(i == j)break;
//change value
swap(arr, i, j);
mid = i;
}
if(mid > 1)
sort(arr, mid);
if(len-mid > 1 && mid != 0)
sort(arr+mid+1, len - mid-1);
}
void printArray(int arr[], int len)
{
int i;
for(i = 0; i< len; i++)
{
printf("%d,", arr[i]);
}
printf("\n");
}
void swap(int arr[], int i, int j)
{
int temp ;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}