Java Program for Comb Sort


The Comb Sort in Java eliminates the smaller values situated to the end of the list and the inversions are removed oby by one. Let us see an example −

Example

 Live Demo

import java.util.Arrays;
public class Demo{
   void comb_sort(int nums[]){
      int len_gap = nums.length;
      float shrink_val = 1.3f;
      boolean swap = false;
      while (len_gap > 1 || swap) {
         if (len_gap > 1) {
            len_gap = (int)(len_gap / shrink_val);
         }
         swap = false;
         for (int i = 0; len_gap + i < nums.length; i++){
            if (nums[i] > nums[i + len_gap]) {
               swap(nums, i, i + len_gap);
               swap = true;
            }
         }
      }
   }
   private static void swap(int nums[], int x, int y) {
      Integer temp = nums[x];
      nums[x] = nums[y];
      nums[y] = temp;
   }
   public static void main(String args[]){
      Demo ob = new Demo();
      int nums[] = {6, 78, 90, -12, -45, 0, -1, 45};
      System.out.println("The original array contains ");
      System.out.println(Arrays.toString(nums));
      ob.comb_sort(nums);
      System.out.println("The sorted array is ");
      System.out.println(Arrays.toString(nums));
   }
}

Output

The original array contains
[6, 78, 90, -12, -45, 0, -1, 45]
The sorted array is
[-45, -12, -1, 0, 6, 45, 78, 90]

A class named Demo contains the ‘comb_sort’ function. Here, the length of the array is defined and if this length is greater than 1, a new ‘len_gap’ is defined that is the length of array divided by 1.3f.

This array is iterated over and the elements in the array are compared and if the element is greater than the element plus a specific ‘len_gap’, the elements are swapped. After this, a simple bubble sort is also performed on the elements. In the main function, the array is defined and an instance of Demo class is defined and the ‘comb_sort’ function is called on the array.

Updated on: 04-Jul-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements