Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active November 17, 2017 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/ecc1cd7776adadb2ff9be73bf980c91e to your computer and use it in GitHub Desktop.
Save anil477/ecc1cd7776adadb2ff9be73bf980c91e to your computer and use it in GitHub Desktop.
Bubble Sort(Optimized)
// 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