使用4种方法来进行数组的排序,解决力扣的第912题。
leetcode 912. 排序数组
方法一:使用直接插入法
空间复杂度:O(1)
时间复杂度:O(n的平方)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArray(int* nums, int numsSize, int* returnSize){
int i,j,temp;
*returnSize=numsSize;
for(int i=0;i<numsSize;i++)
{
if(nums[i]<nums[i-1])
{
temp=nums[i];
for(j=i-1;j>=0&&nums[j].temp;j--)
{
nums[j+1]=nums[j];
}
nums[j+1]=temp;
}
}
}
方法二:折半插入排序
空间复杂度:O(1)
时间复杂度:O(n的平方)
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* sortArray(int* nums, int numsSize, int* returnSize){
int i,j,temp;
*returnSize=numsSize;
for(int i=1;i<numsSize;i++)
{
if(nums[i]<nums[i-1])
{
temp=nums[i];
for(j=i-1;j>=0&&nums[j]>temp;j--)
{
nums[j+1]=nums[j];
}
nums[j+1]=temp;
}
}
return nums;
}
方法三、快速排序
时间复杂度:O(nlogn)。
空间复杂度:O(n)。
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int partition(int *nums,int low,int high)
{
if(low<high)
{
int pivot=nums[low];
while(low<high){
while(low<high&&nums[high]>=pivot)
--high;
nums[low]=nums[high];
while(low<high&&nums[low]<=pivot)
++low;
nums[high]=nums[low];
}
nums[low]=pivot;
}
return low;
}
void QuickSort(int *nums,int low,int high){
if(low>=high)
return ;
int pivotops=partition(nums,low,high);
QuickSort(nums,low,pivotops-1);
QuickSort(nums,pivotops+1,high);
}
int* sortArray(int* nums, int numsSize, int* returnSize){
QuickSort(nums,0,numsSize-1);
*returnSize=numsSize;
return nums;
}
方法四 选择排序
首先从未排序的序列中找到最小大元素,存放到排序序列的起始位置,再从剩余未排序未排序元素中继续寻找最小大元素,然后放到已排序序列的末尾,重复上一步,直到所有元素均排序完毕。
int* sortArray(int* nums, int numsSize, int* returnSize){
*returnSize = numsSize;
if (numsSize == 1) {
return;
}
//! 已排序区间角标
int point = 0;
//! 定位最小值 角标
int k = point;
for (int i = 0; i < numsSize-1; ++i) {
//! 未排序最小值,默认取已排序的最后一个元素
int temp = nums[point];
int k = point;
for (int j = point; j < numsSize; ++j) {
if (temp > nums[j]) {
temp = nums[j];
k = j;
}
}
//! 交换
nums[k] = nums[point];
nums[point] = temp;
//! 区间+1
++point;
}
return nums;
}