-
Notifications
You must be signed in to change notification settings - Fork 102
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
-Algorithm for insertion sort (#284)
- Loading branch information
1 parent
701636e
commit fe24614
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/*INSERTION SORT--> | ||
-> Insertion sort is a simple sorting algorithm that works by building a sorted array one element at a time. | ||
It is considered an ” in-place ” sorting algorithm, meaning it doesn’t require any additional memory space beyond the original array. | ||
-> The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked | ||
and placed at the correct position in the sorted part. | ||
* ALGORITHM --> | ||
1) Input :- An array of integers. | ||
2) We will take an outer loop, which iterate from zeroth index of an array to (length of array - 1)th index. | ||
:)This loop select an element in each iteration from the unsorted array. | ||
:)The first element of the array is assumed to be sorted. | ||
3) For each element, compare it with the elements before it(or compare it with sorted sub-array) by using inner loop. | ||
:)Shift all the elements in sorted sub-array that is greater than the value to be sorted using swapping function inside inner loop. | ||
:)Insert current element into it's correct position. | ||
4) Output -> Sorted array in ascending order. | ||
Time complexity -> Best Case=O(n):when the array is already sorted. | ||
Average and Worst Case = O(n^2):due nested loops | ||
*/ | ||
|
||
class InsertionSort{ | ||
static void insertionSort(int[] arr,int n){ | ||
for(int i=0;i<n;i++){ | ||
int j=i; | ||
while(j>0 && arr[j-1]>arr[j]){ | ||
int temp=arr[j-1]; | ||
arr[j-1]=arr[j]; | ||
arr[j]=temp; | ||
j--; | ||
} | ||
} | ||
|
||
}public static void main(String [] args){ | ||
int[] arr={7,9,24,27,2,15}; | ||
int n=arr.length; | ||
insertionSort(arr,n); | ||
System.out.println("After insertion sort"); | ||
for(int i=0;i<n;i++){ | ||
System.out.print(arr[i]+" "); | ||
|
||
} | ||
} | ||
} |