Last active
November 17, 2017 11:13
-
-
Save anil477/ecc1cd7776adadb2ff9be73bf980c91e to your computer and use it in GitHub Desktop.
Bubble Sort(Optimized)
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
// Best - O(n) | |
// Average - O(n^2) | |
// Worst - O(n^2) | |
// Space - O(1) | |
// Java program for implementation of Bubble Sort | |
class BubbleSort | |
{ | |
void bubbleSort(String arr[]) | |
{ | |
int n = arr.length; | |
int j = 0; | |
boolean swap; | |
// last element don't need to be considered as it will be in right position by itself if all other are in position | |
for (int i = 0; i < n-1; i++){ | |
swap = false; | |
// we don't need to consider last - 1 element as we check j+1 element | |
for (j = 0; j < n-i-1; j++){ | |
int compare = arr[j].compareTo(arr[j+1]); | |
if (compare>0) | |
{ | |
String temp = arr[j]; | |
arr[j] = arr[j+1]; | |
arr[j+1] = temp; | |
swap = true; | |
} | |
} | |
if(swap == false) | |
break; | |
} | |
} | |
/* Prints the array */ | |
void printArray(String arr[]) | |
{ | |
int n = arr.length; | |
for (int i=0; i<n; ++i) | |
System.out.print(arr[i] + " "); | |
System.out.println(); | |
} | |
// Driver method to test above | |
public static void main(String args[]) | |
{ | |
BubbleSort ob = new BubbleSort(); | |
String arr[] = {"anil", "sunil", "ani", "arch"}; | |
// int arr[] = {4, 9, 10, 12}; | |
ob.bubbleSort(arr); | |
System.out.println("Sorted array"); | |
ob.printArray(arr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment