-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort an Array.java
More file actions
62 lines (52 loc) · 1.86 KB
/
Sort an Array.java
File metadata and controls
62 lines (52 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//this solution is based on QuickSort
public int[] sortArray(int[] nums) {
if (nums == null || nums.length == 0) {
return nums;
}
quickSort(nums, 0, nums.length - 1);
return nums;
}
private void quickSort(int[] nums, int start, int end) {
if (start >= end) return;
int left = start, right = end;
// Ideally, numbers are approximately increasing, which means the middle number is most likey the median number.
// The closer pivot is to the median number, the less swapping and recursion we need to do.
int pivot = nums[left + (right - left) / 2];
// with (left <= right), we can end with:
// 1. x, x, x, right, left, x, x, x,
// or
// 2. x, x, x, right, pivot, left, x, x, x
// easy to divide without boundary issues
while (left <= right) {
// if we put nums[left] <= pivot, for array like [2, 1], 1 swap with itself and leads to dead loop
while (left <= right && nums[left] < pivot) left++;
while (left <= right && nums[right] > pivot) right--;
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
quickSort(nums, start, right);
quickSort(nums, left, end);
}
//this solution is based on insertion sort
class Solution {
public int[] sortArray(int[] nums) {
int n=nums.length;
for(int i=0; i<n; i++){
int minNum = i;
for(int j=i; j<n; j++){
if( nums[j] < nums[minNum]){
minNum = j;
}
}
int temp = nums[i];
nums[i] = nums[minNum];
nums[minNum] = temp;
}
return nums;
}
}