Bubble Sort in java

No comments
Sorting is the process of putting the elements in a specific sequence or order it could be a ascending order or descending order.In this article we will write code for sorting an array of integers using bubble sort algorithm.Before starting the actual coding ,we will try to understand the algorithm used in bubble sort.
Suppose we have an array of some integers and we want to sort it in ascending order ie. smallest to the largest integer.In bubble sort we will compare each element of the array with its adjacent next element, and there could arise two conditions either the element will be greater then the next adjacent element or it will be less then the next adjacent element.
If the element is greater then the next adjacent element then we will swap the elements and move to the next step.
If the element is less then the next adjacent element then without doing anything we will move to our next step.
We will keep on doing this until all the elements are sorted.
Now as we have understood the flow of the program , we can start writing the code.
Program-

package in.blogger.tutorialsinn;

public class BubbleSort {

 public static void main(String[] args) {

  int arr[] = { 4, -3, 2, 6, 1 };

  for (int n = 1; n <= arr.length; n++) {
   for (int i = 0; i < arr.length - 1; i++) {

    if (arr[i] > arr[i + 1]) {
     int temp = arr[i];
     arr[i] = arr[i + 1];
     arr[i + 1] = temp;
    }

   }
  }

  for (int i = 0; i < arr.length; i++) {
   System.out.print(" " + arr[i]);

  }
 }

}


Output-
-3 1 2 4 6
I hope you have understood the bubble sort for an integer array,it was a very basic sorting algorithm and we will add some more important sorting algorithms in our next articles so stay in touch.

No comments :

Post a Comment