Saturday, August 29, 2020

Bubble Sort on String Array

Bubble Sort on string array.
1. Input array sthould be String array.
2.we have to use string compareTo() method to compare the adjacent Strings
package dataStructure;

class BubbleSortOnStringArray {
 public static void main(String[] args) {
  String data[] = { "Kumar", "Bubble", "Sandeep", "Jitendra", "Pawan" };
  System.out.println("Input data for Sorting : ");
  printArray(data);
  BubbleSort(data);
 }

 static void BubbleSort(String[] array) {
  int n, c, d;
  n = array.length;
  for (c = 0; c < (n - 1); c++) {
   for (d = 0; d < n - c - 1; d++) {
    if (array[d].compareTo(array[d + 1]) < 0) /* For descending order use < */
    {
     // swap elements
     swap(d, array);
    }
   }
  }

  System.out.println("Output - Sorted data:");
  printArray(array);
 }

 static void swap(int num, String[] array) {
  String swap = array[num];
  array[num] = array[num + 1];
  array[num + 1] = swap;
 }

 static void printArray(String[] array) {
  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i] + " ");
  }
  System.out.println();

 }
}
Output:
Input data for Sorting : 
Kumar 
Bubble 
Sandeep 
Jitendra 
Pawan 

Output - Sorted data:
Sandeep 
Pawan 
Kumar 
Jitendra 
Bubble 

No comments:

Post a Comment