-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDSA-lab5(b)-Insertion_Sort
More file actions
63 lines (50 loc) · 1.52 KB
/
DSA-lab5(b)-Insertion_Sort
File metadata and controls
63 lines (50 loc) · 1.52 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
import java.util.Scanner;
/**
* InsertionSort Program
* ---------------------
* This program sorts an array using Insertion Sort algorithm.
*
* Time Complexity:
* - Best Case: O(n)
* - Worst Case: O(n^2)
*/
public class InsertionSort {
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 insertion sort function
insertionSort(arr);
// Displaying sorted array
System.out.println("Sorted array (Insertion Sort):");
for (int num : arr) {
System.out.print(num + " ");
}
sc.close(); // closing scanner
}
/**
* Insertion Sort Algorithm
* Builds sorted array one element at a time
*/
public static void insertionSort(int[] arr) {
int n = arr.length;
// Traverse from second element to end
for (int i = 1; i < n; i++) {
int key = arr[i]; // element to be inserted
int j = i - 1;
// Shift elements greater than key to right
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// Place key at correct position
arr[j + 1] = key;
}
}
}