Skip to content

Commit c45ff75

Browse files
Added the Insertion Sort Algorithm
1 parent 58fae44 commit c45ff75

2 files changed

Lines changed: 27 additions & 6 deletions

File tree

‎src/com/sketch/Main.java‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,30 @@
11
package com.sketch;
22

3-
import com.sketch.sort.quicksort.QuickSort;
3+
import com.sketch.sort.insertionsort.InsertionSort;
44

55
import java.util.Arrays;
66
import java.util.Random;
77

88
public class Main {
99
public static void main(String[] args){
10-
int[] unsortedArray = new int[100];
10+
int[] unsortedArray = new int[10000];
1111
Random random = new Random();
1212
for(int i = 0; i < unsortedArray.length; i++){
13-
unsortedArray[i] = random.nextInt(20);
13+
unsortedArray[i] = random.nextInt(50);
1414
}
1515

1616
int[] unsortedArrayResult = new int[unsortedArray.length];
1717
System.arraycopy(unsortedArray, 0, unsortedArrayResult, 0, unsortedArray.length);
1818

19-
QuickSort.sort(unsortedArrayResult, 0, unsortedArrayResult.length - 1);
19+
long startTime = System.nanoTime();
2020

21-
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArray));
22-
System.out.println("Actual Value Index: " + Arrays.toString(unsortedArrayResult));
21+
InsertionSort.sort(unsortedArrayResult);
22+
23+
long endTime = System.nanoTime();
24+
double duration = (endTime - startTime) / 1_000_000.0;
25+
26+
System.out.println("Default Array: " + Arrays.toString(unsortedArray));
27+
System.out.println("Sorted Array: " + Arrays.toString(unsortedArrayResult));
28+
System.out.println("Execution Time: " + duration + "ms");
2329
}
2430
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package com.sketch.sort.insertionsort;
2+
3+
public class InsertionSort {
4+
public static void sort(int[] array){
5+
for(int i = 1; i < array.length; i++){
6+
int currentValue = array[i];
7+
int j = i - 1;
8+
while (j >= 0 && array[j] > currentValue){
9+
array[j + 1] = array[j];
10+
j--;
11+
}
12+
array[j + 1] = currentValue;
13+
}
14+
}
15+
}

0 commit comments

Comments
 (0)