Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.
分析
bubble sort
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class Solution {
/**
* @param A an integer array
* @return void
*/
public void sortIntegers(int[] A) {
// Write your code here
for(int i = 0; i < A.length - 1; ++i){
for(int j = 0; j < A.length - i -1; ++j){
if( A[j] > A[j+1]) swap(A, j, j+1);
}
}
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} |
selection sort
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class Solution {
/**
* @param A an integer array
* @return void
*/
public void sortIntegers(int[] A) {
// Write your code here
for(int i = 0; i < A.length; ++i){
int min_i = i;
for(int j = i; j < A.length; ++j){
if(A[min_i] >= A[j])
min_i = j;
}
swap(A, i, min_i);
}
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} |
insert sort