-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpractical02.java
51 lines (41 loc) · 1.27 KB
/
practical02.java
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
// Sort the given array using Selection sort
import java.util.Scanner;
class practical02 {
public static void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void selectionSort(int arr[], int n) {
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
if (min != i) {
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of elements in array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("\nEnter " + n + " elements: ");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.println("\nArray before sorting: ");
printArray(arr, n);
selectionSort(arr, n);
System.out.println("\nArray after sort: ");
printArray(arr, n);
sc.close();
}
}