Created
January 29, 2024 12:19
-
-
Save juliettegodyere/37ebb7c8c310cd5b341fc1cd93ddb153 to your computer and use it in GitHub Desktop.
Optimised Bubble Sort
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
Bubble sort progressively moves the largest element to the last position by iterating through the array and swapping adjacent elements until the entire array is sorted. During each iteration of the outer loop, the largest element finds its way to the last index. To enhance efficiency, the inner loop only needs to run up to n-i-1, where n is the total number of elements and i is the current iteration of the outer loop. | |
public void sort(int arr[]){ | |
int n = arr.length; | |
for(int i = 0; i < n; i++){ | |
for(int j = 0; j < n-i-1; j++){ | |
if(arr[j] > arr[j+1]){ | |
int temp = arr[j]; | |
arr[j] = arr[j+1]; | |
arr[j+1] = temp; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment