Selection sort : In selection sort we will divide the Array in 2 parts , sorted and unsorted and select the min element from unsorted and will copy to sorted array.
Time Complexity for selection sort also is O(n^2).space complexity for bubble sort will be O(1).
class SelectionSort {
public static void sort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[min]) {
min = j;
}
}
swap(array, i, min);
}
}
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void print(int[] array) {
System.out.print("[");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
public static void main(String[] args) {
int[] A = {111, 80, 14, 21, 19, 31, 19, 121, 10, 190, 80, 6, 7};
sort(A);
print(A);
}
}
Please have a look to the source code of all sorting method from below link
Comments
Post a Comment