Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active June 26, 2017 08:02
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/9865ccb283ffcd50f036d5bd40066646 to your computer and use it in GitHub Desktop.
Save anil477/9865ccb283ffcd50f036d5bd40066646 to your computer and use it in GitHub Desktop.
Bubble Sort
// Java program for implementation of Bubble Sort
class BubbleSort
{
void bubbleSort(int 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++){
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swap = true;
}
}
if(swap == false)
break;
}
}
/* Prints the array */
void printArray(int 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();
int arr[] = {164, 34, 2, 2229};
// 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