Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Algorithm: Bubble Sort
- Input: Array ary of sortable values
- Output:s Array ary in ascending order
- ***************************/
- import java.util.Scanner;
- public class BubbleSortExample {
- static void bubbleSort(int[] arr) {
- int n = arr.length;
- int temp = 0;
- boolean isSorted = false;
- // while ( array ary is not sorted )
- while (!isSorted){
- isSorted = true; // Sorted when we loop without swap
- // for ( each adjacent pair of items )
- for(int j=1; j <= n-1; j++){
- // if ( the pair of items are out of order )
- if(arr[j-1] < arr[j]){
- // swap the pair of items
- temp = arr[j-1];
- arr[j-1] = arr[j];
- arr[j] = temp;
- isSorted = false;
- }
- }
- }
- }
- public static void main(String[] args) {
- int arr[] ={3,60,35,2,45,320,5};
- System.out.println("Array Before Bubble Sort");
- for(int i=0; i < arr.length; i++){
- System.out.print(arr[i] + " ");
- }
- System.out.println();
- bubbleSort(arr);//sorting array elements using bubble sort
- System.out.println("Array After Bubble Sort");
- for(int i=0; i < arr.length; i++){
- System.out.print(arr[i] + " ");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement