Skip to content

Update InsertionSort.java #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 49 additions & 32 deletions InsertionSort.java
Original file line number Diff line number Diff line change
@@ -1,33 +1,50 @@
// Java program for implementation of Insertion Sort
class InsertionSort{
void sort(int arr[]){
int n = arr.length;
for (int i=1; i<n; ++i){
int key = arr[i];
int j = i-1;

while (j>=0 && arr[j] > key){
arr[j+1] = arr[j];
j = j-1;
}
arr[j+1] = key;
}
}

static void printArray(int arr[]){
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

public static void main(String args[]){
int arr[] = {12, 11, 13, 5, 6};

InsertionSort ob = new InsertionSort();
ob.sort(arr);

printArray(arr);
}
// Java program for implementation of Insertion Sort
class InsertionSort
{
/*Function to sort array using insertion sort*/
void sort ( int A[]) {
int n=A.length;

for( int i = 0 ;i < n ; i++ ) {
/*storing current element whose left side is checked for its
correct position .*/

int temp = A[ i ];
int j = i;

/* check whether the adjacent element in left side is greater or
less than the current element. */

while( j > 0 && temp < A[j-1]) {

// moving the left side element to one position forward.
A[j] = A[j-1];
j= j - 1;

}
// moving current element to its correct position.
A[ j ] = temp;
}
}

/* A utility function to print array of size n*/
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6};

InsertionSort ob = new InsertionSort();
ob.sort(arr);

printArray(arr);
}
}