Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SortingNamesWithTime {
- static long aviTime;
- static long usifTime;
- public static void aviSort(String[] names) {
- long startTime = Utils.getCurrentTime();
- int n = names.length; // number of names in the array
- for (int i = n - 1; i > 0; i--) {
- // find and position item at index i - will not be moved from this
- // index
- for (int j = 0; j < i; j++) {
- if (names[j].compareTo(names[j + 1]) > 0) {
- // if not correctly ordered then swap names
- String temp = names[j];
- names[j] = names[j + 1];
- names[j + 1] = temp;
- }
- }
- // now starting from position i the array is finally sorted
- }
- long endTime = Utils.getCurrentTime();
- aviTime = endTime - startTime;
- }
- public static void usifSort(String[] names) {
- long startTime = Utils.getCurrentTime();
- int n = names.length; // number of names in the array
- int i = 0; // start sorting from the beginning of the array
- while (i < n - 1) { // if not all sorted
- if (names[i].compareTo(names[i + 1]) > 0) {
- // if not correctly ordered then swap names
- String temp = names[i];
- names[i] = names[i + 1];
- names[i + 1] = temp;
- i = 0; // start sorting from the beginning of the array
- } else {
- // now all items until position i in the array is sorted
- i = i + 1; // move to the next position
- }
- }
- long endTime = Utils.getCurrentTime();
- usifTime = endTime - startTime;
- }
- public static void main(String[] args) {
- // number of students
- int n = 90;
- // get random names
- String[] arr1 = Utils.getRandomNames(n);
- // make a copy of the names
- String[] arr2 = Utils.getNamesCopy(arr1);
- // print source data
- // arr1 has the same data in the same order as arr2
- Utils.printArray(arr1, "\ndata before sorting - unsorted");
- // Avi sorting the data array - arr1
- aviSort(arr1);
- // Usif sorting the data array - arr2
- usifSort(arr2);
- // print the two sorted arrays
- Utils.printArray(arr1, arr2, "\ndata after sorting - Sorted",
- "Avi array", "Usif array");
- System.out.printf("\nAvi sorted %d names in %d ms\n", n, aviTime);
- System.out.printf("Usif sorted %d names in %d ms\n", n, usifTime);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement