Skip to content
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

Added insertion sort in java #602

Closed
wants to merge 3 commits into from
Closed
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
35 changes: 35 additions & 0 deletions insertion_sort/Java/insertion_sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.Scanner;

public class insertion_sort {

public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow

System.out.print("Enter the number of elements : ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " + n + " elements :");
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();

insertionSort(arr);

System.out.println("\nThe sorted array : ;");
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println();
}

static void insertionSort(int arr[]) {
int len = arr.length, tmp, j;
for (int i = 1; i < len; i++) {
tmp = arr[i];
for (j = i; j > 0; j--) {
if (arr[j - 1] > tmp)
arr[j] = arr[j - 1];
else
break;
}
arr[j] = tmp;
}
}
}