1.快速排序
class Solution {
public int[] sortArray(int[] nums) {
int l = 0;
int h = nums.length-1;
quickSort(nums, l, h);
return nums;
}
//一趟快速排序
int partion (int[] nums, int l, int h){
int pivot = nums[l];
while(l < h){
while(l < h && nums[h] >= pivot) --h;
swap(nums, l ,h);
while(l < h && nums[l] <= pivot) ++l;
swap(nums, l ,h);
}
return l;
}
//递归实现快速排序算法
void quickSort(int[] nums, int l, int h){
if(l < h){
int pivotloc = partion(nums, l, h);
quickSort(nums, l, pivotloc-1);
quickSort(nums, pivotloc+1, h);
}
}
//交换数组元素的函数
void swap(int[] nums, int l , int h){
int temp = nums[l];
nums[l] = nums[h];
nums[h] = temp;
}
/*注意下面代码无法实现数组元素交换。因为形参的不直接影响实参的值。这种方法只是交换了两个形参的值,对实参并没有影响。上面的方法是因为传入的参数实际上是地址,改变了地址中的值所以数组也就变了。
void swap(int x, int y){
int temp = 0;
temp = x;
x = y;
y = temp;
}
*/
}
- 插入排序
class Solution {
public int[] sortArray(int[] nums) {
insertSort(nums);
return nums;
}
void insertSort(int[] nums){
for (int i = 1; i< nums.length; i++){
int r = nums[i];
for (int j = i - 1; j >= 0; j--){
if(r < nums[j]){
nums[j+1] = nums[j];
nums[j] = r;
}else{
break;
}
}
}
}
}