Sort Integers
Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.
Example
Given [3, 2, 1, 4, 5], return [1, 2, 3, 4, 5].
selection sort
From A[0] to A[A.length - 1], find the minimum and swap with A[0].
From A[1] to A[A.length - 1], find the minimum and swap with A[1].
From A[2] to A[A.length - 1], find the minimum and swap with A[2].
...
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++) { int min = A[i]; int minIndex = i; for (int j = i + 1; j < A.length; j++) { if (A[j] < min) { min = A[j]; index = j; } } int tmp = A[i]; A[i] = A[minIndex]; A[minIndex] = tmp; } } }
insertion sort
From A[1], if A[1] < A[0], swap them.
From A[2], if A[2] < A[1], swap them. Now if A[1] < A[0], swap them.
From A[3], if A[3] < A[2], swap them. Now if A[2] < A[1], swap them. Now if A[1] < A[0], swap them.
...
Every time A[i] compares with its previous element and inserts to the proper position.
public class Solution { /** * @param A an integer array * @return void */ public void sortIntegers(int[] A) { // Write your code here for (int i = 1; i < A.length; i++) { int currIndex = i; while (currIndex != 0 && A[currIndex] < A[currIndex - 1]) { int tmp = A[currIndex]; A[currIndex] = A[currIndex - 1]; A[currIndex - 1] = tmp; currIndex--; } } } }
bubble sort
From A[1] to A[A.length - 1], if A[i - 1] > A[i], swap them. Now A[A.length - 1] is the maximum number.
From A[1] to A[A.length - 2], if A[i - 1] > A[i], swap them. Now A[A.length - 2] is the 2nd maximum number.
From A[1] to A[A.length - 3], if A[i - 1] > A[i], swap them. Now A[A.length - 3] is the 3rd maximum number.
...
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++) { for (int j = 1; j < A.length - i; j++) { if (A[j - 1] > A[j]) { int tmp = A[j - 1]; A[j - 1] = A[j]; A[j] = tmp; } } } } }