Skip to content

Insertion Sort Algorithm in Java #6276

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

Closed
Show file tree
Hide file tree
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
40 changes: 40 additions & 0 deletions Sorting/BubbleSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/**
Copy link
Collaborator

Choose a reason for hiding this comment

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

* BubbleSort.java
* This program implements the Bubble Sort algorithm.
* Time Complexity: O(n^2)
*/

public class BubbleSort {

public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;

for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;

swapped = true;
}
}

// If no two elements were swapped, array is sorted
if (!swapped)
break;
}
}

public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
bubbleSort(arr);
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
33 changes: 33 additions & 0 deletions Sorting/InsertionSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
Copy link
Collaborator

Choose a reason for hiding this comment

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

* InsertionSort.java
* This program implements the Insertion Sort algorithm.
* Time Complexity: O(n^2) in worst case, O(n) in best case (already sorted).
*/

public class InsertionSort {

public static void insertionSort(int[] arr) {
// Loop from the second element to the end
for (int i = 1; i < arr.length; i++) {
int key = arr[i]; // Store the current element to be inserted
int j = i - 1;

// Move elements of arr[0..i-1], that are greater than key,
// to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // Shift element to the right
j = j - 1;
}
arr[j + 1] = key; // Insert the key into its correct position
}
}

public static void main(String[] args) {
int[] arr = {29, 10, 14, 37, 13};
insertionSort(arr);
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}