Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.
Example
Example 1:
Input: [3, 2, 1, 4, 5]
Output: [1, 2, 3, 4, 5]
Explanation:
return the sorted array.
Example 2:
Input: [1, 1, 2, 1, 1]
Output: [1, 1, 1, 1, 2]
Explanation:
return the sorted array.
思路:经典排序算法:merge sort和quick sort,注意merge sort merge的时候,index起始点是start,不是0;
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
// 1. Merge sort;
// 2. Quick sort;
public void sortIntegers(int[] A) {
if(A == null || A.length == 0) {
return;
}
int[] temp = new int[A.length];
mergeSort(A, 0, A.length -1, temp);
}
private void mergeSort(int[] A, int start, int end, int[] temp) {
if(start >= end) {
return;
}
int mid = start + (end - start) / 2;
mergeSort(A, start, mid, temp);
mergeSort(A, mid+1, end, temp);
merge(A, start, end, temp);
}
private void merge(int[] A, int start, int end, int[] temp) {
int mid = start + (end - start) / 2;
int astart = start;
int aend = mid;
int bstart = mid+1;
int bend = end;
int index = start; // 注意index = start,不是0;
while(astart <= aend && bstart <= bend) {
if(A[astart] < A[bstart]) {
temp[index++] = A[astart++];
} else {
temp[index++] = A[bstart++];
}
}
while(astart <= aend) {
temp[index++] = A[astart++];
}
while(bstart <= bend) {
temp[index++] = A[bstart++];
}
for(int i = start; i <= end; i++) {
A[i] = temp[i];
}
}
}
quick sort,要熟悉两个while一个if的模板;
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers(int[] A) {
// quick sort;
if(A == null || A.length == 0) {
return;
}
quickSort(A, 0, A.length - 1);
}
private void quickSort(int[] A, int start, int end) {
if(start >= end) {
return;
}
int mid = start + (end - start) / 2;
int pivot = A[mid];
int left = start;
int right = end;
while(left <= right) {
while(left <= right && A[left] < pivot) {
left++;
}
while(left <= right && A[right] > pivot) {
right--;
}
if(left <= right) { // 这个if很关键,跟上面两个while是同样的判断;
int temp = A[left];
A[left] = A[right];
A[right] = temp;
left++;
right--;
}
}
quickSort(A, start, right);
quickSort(A, left, end);
}
}