Java Program for Bitonic Sort

JavaObject Oriented ProgrammingProgramming

In Bitonic Sort, the comparision is in predefined sequence (Bitonic sequence), not dependent on the data to be sorted. Let us see an example for Bitonic Sort Java program −

Example

 Live Demo

public class Demo{
   void compare_swap(int my_arr[], int i, int j, int direction){
      if ((my_arr[i] > my_arr[j] && direction == 1) || (my_arr[i] < my_arr[j] && direction == 0)){
         int temp = my_arr[i];
         my_arr[i] = my_arr[j];
         my_arr[j] = temp;
      }
   }
   void merge_vals(int my_arr[], int low, int cnt, int direction){
      if (cnt>1){
         int k = cnt/2;
         for (int i=low; i<low+k; i++)
         compare_swap(my_arr,i, i+k, direction);
         merge_vals(my_arr,low, k, direction);
         merge_vals(my_arr,low+k, k, direction);
      }
   }
   void sort_vals(int my_arr[], int low, int cnt, int direction){
      if (cnt>1){
         int k = cnt/2;
         sort_vals(my_arr, low, k, 1);
         sort_vals(my_arr,low+k, k, 0);
         merge_vals(my_arr, low, cnt, direction);
      }
   }
   static void print_vals(int my_arr[]){
      int n = my_arr.length;
      for (int i=0; i<n; ++i)
      System.out.print(my_arr[i] + " ");
      System.out.println();
   }
   public static void main(String args[]){
      int my_arr[] = {12, 67, 91, 54, 72, 32, 11, 0};
      int up = 1;
      Demo my_ob = new Demo();
      System.out.println("The object of the class has been created.");
      my_ob.sort_vals(my_arr, 0, my_arr.length, up);
      System.out.println("The array after performing bitonic sort is");
      print_vals(my_arr);
   }
}

Output

The object of the class has been created.
The array after performing bitonic sort is
0 11 12 32 54 67 72 91

A class named Demo contains the ‘compare_swap’ function that takes array as parameter, and checks the direction in which the sorting has to be performed. Accordingly, the elements are swapped. Another function named ‘merge_vals’ is defined that iterates through the array and calls the ‘compare_swap’ function with specific values.

Next, the ‘merge_vals’ function is called with various parameters. Another function named ‘sort_vals’ is defined that is called inside the function with different values. Then these sorted values

are merged. A static function named ‘print_vals’ is defined that takes the array as parameter and runs the ‘for’ loop through the elements of the array and prints it on the console.

The main function defines an array and a value for ‘up’ variable. A new class object is created and the ‘sort_now’ function is called on the array defined. Then, the output is printed on the console.

raja
Published on 04-Jul-2020 09:49:11
Advertisements