mmayoub

lab, SortingNames

Jul 5th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. public class SortingNames {
  2.  
  3.     public static void aviSort(String[] names) {
  4.         int n = names.length; // number of names in the array
  5.  
  6.         for (int i = n - 1; i > 0; i--) {
  7.             // find and position item at index i - will not be moved from this
  8.             // index
  9.  
  10.             for (int j = 0; j < i; j++) {
  11.                 if (names[j].compareTo(names[j + 1]) > 0) {
  12.                     // if not correctly ordered then swap names
  13.                     String temp = names[j];
  14.                     names[j] = names[j + 1];
  15.                     names[j + 1] = temp;
  16.                 }
  17.             }
  18.  
  19.             // now starting from position i the array is finally sorted
  20.         }
  21.     }
  22.  
  23.     public static void usifSort(String[] names) {
  24.         int n = names.length; // number of names in the array
  25.  
  26.         int i = 0; // start sorting from the beginning of the array
  27.  
  28.         while (i < n - 1) { // if not all sorted
  29.             if (names[i].compareTo(names[i + 1]) > 0) {
  30.                 // if not correctly ordered then swap names
  31.                 String temp = names[i];
  32.                 names[i] = names[i + 1];
  33.                 names[i + 1] = temp;
  34.                 i = 0; // start sorting from the beginning of the array
  35.             } else {
  36.                 // now all items until position i in the array is sorted
  37.  
  38.                 i = i + 1; // move to the next position
  39.             }
  40.         }
  41.     }
  42.  
  43.     public static void main(String[] args) {
  44.         // number of students
  45.         int n = 8;
  46.         // get random names
  47.         String[] arr1 = Utils.getRandomNames(n);
  48.         // make a copy of the names
  49.         String[] arr2 = Utils.getNamesCopy(arr1);
  50.  
  51.         // print source data
  52.         // arr1 has the same data in the same order as arr2
  53.         Utils.printArray(arr1, "\ndata before sorting - unsorted");
  54.  
  55.         // Avi sorting the data array - arr1
  56.         aviSort(arr1);
  57.         // Usif sorting the data array - arr2
  58.         usifSort(arr2);
  59.  
  60.         // print the two sorted arrays
  61.         Utils.printArray(arr1, arr2, "\ndata after sorting - Sorted",
  62.                 "Avi array", "Usif array");
  63.  
  64.     }
  65. }
Add Comment
Please, Sign In to add comment