今天再刷题的时候遇见了一个需要用到快速选择的题目,所以需要写一个快排,但是我发现我竟然忘了。。。
来复习下
#include <stdio.h>
#include <stdlib.h>
void swap(int* nums, int a, int b)
{
int t = nums[a]; nums[a] = nums[b]; nums[b] = t; return;
}
void quick_sort(int* nums, int left, int right)
{
if(left >= right) return;
int last = left;
int i;
for(i=left+1; i<=right; i++)
{
if(nums[i] <= nums[left])
{
swap(nums, ++last, i);
}
}
swap(nums, last, left);
quick_sort(nums, left, last-1);
quick_sort(nums, last+1, right);
return;
}
int* sortArray(int* nums, int numsSize){
quick_sort(nums, 0, numsSize-1);
int* sorted_nums = malloc(sizeof(int) * numsSize);
int i;
for(i=0; i<numsSize; ++i)
{
sorted_nums[i] = nums[i];
}
return sorted_nums;
}
int main()
{
int nums[] = {5,1,1,2,0,0};
int* res = sortArray(nums, 6);
int i;
for(i=0; i<6; ++i)
{
printf("%d ", res[i]);
}
printf("\n");
return 0;
}