-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSA-lab5(c)-Selection_Sort
More file actions
65 lines (52 loc) · 1.7 KB
/
DSA-lab5(c)-Selection_Sort
File metadata and controls
65 lines (52 loc) · 1.7 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
63
64
65
import java.util.Scanner;
/**
* SelectionSort Program
* ---------------------
* This program sorts an array using Selection Sort algorithm.
*
* Time Complexity:
* - Best Case: O(n^2)
* - Worst Case: O(n^2)
*/
public class SelectionSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Taking input from user
System.out.print("Enter number of elements: ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt(); // storing input values
}
// Calling selection sort function
selectionSort(arr);
// Displaying sorted array
System.out.println("Sorted array (Selection Sort):");
for (int num : arr) {
System.out.print(num + " ");
}
sc.close(); // closing scanner
}
/**
* Selection Sort Algorithm
* Repeatedly selects the minimum element and places it at correct position
*/
public static void selectionSort(int[] arr) {
int n = arr.length;
// Traverse through entire array
for (int i = 0; i < n - 1; i++) {
int minIndex = i; // assume current index is minimum
// Find the minimum element in remaining array
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j; // update index of minimum element
}
}
// Swap the found minimum element with first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}