Note: In Selection Sort elements are swap "n" times in wrost case.
Steps:-
Steps:-
- First it will compare for element for first position and check with all elements if find min then swap element.
- Check for second element and swap so on..
- So in this way its only swap element only "n" times.
- Selection sort is beter then Bubble sort. Because in bubble sort it swap elements n*(n-1) times.
- Worst-case space complexity: O(1) auxiliary.
- Best-case performance: О(n2) comparisons.
- Worst-case performance: О(n2) comparisons.
package dataStructure;
public class SelectionSort {
public static void main(String[] args) {
int data[] = { 4, -5, 2, 6, 1 };
System.out.print("Input data for Sorting : ");
printArray(data);
SelectionSort(data);
}
static void SelectionSort(int[] array) {
int n, c, d;
n = array.length;
int minIndex;
for (c = 0; c < (n - 1); c++) {
minIndex = c;
for (d = c + 1; d < n; d++) {
if (array[d] < array[minIndex]) {
minIndex = d;
}
}
// swap elements
swap(minIndex, c, array);
printArray(array);
}
System.out.print("Output - Sorted data:");
printArray(array);
}
static void swap(int minIndex, int currIndex, int[] array) {
int swap = array[currIndex];
array[currIndex] = array[minIndex];
array[minIndex] = swap;
}
static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}
Output:
Input data for Sorting : 4 -5 2 6 1
-5 4 2 6 1
-5 1 2 6 4
-5 1 2 6 4
-5 1 2 4 6
Output - Sorted data:-5 1 2 4 6
No comments:
Post a Comment