Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SortingNamesWithCounter {
- static long aviWork;
- static long usifWork;
- public static void aviSort(String[] names) {
- int counter = 0;
- int n = names.length; // number of names in the array
- counter += 2; // get array length and saving to variable
- int i;
- for (i = n - 1, counter += 2; i > 0; i--, counter++) {
- // find and position item at index i - will not be moved from this
- // index
- counter += 1; // check logical condition
- int j;
- for (j = 0, counter++; j < i; j++, counter++) {
- counter++; // check for logical condition
- if (names[j].compareTo(names[j + 1]) > 0) {
- // if not correctly ordered then swap names
- String temp = names[j];
- counter++;
- names[j] = names[j + 1];
- counter++;
- names[j + 1] = temp;
- counter++;
- }
- counter += 1; // check if condition
- counter += 1; // update j
- }
- counter += 1; // update i
- // now starting from position i the array is finally sorted
- }
- aviWork = counter;
- }
- public static void usifSort(String[] names) {
- int counter = 0;
- int n = names.length; // number of names in the array
- counter += 2; // get array length and saving to variable
- int i = 0; // start sorting from the beginning of the array
- counter++;
- while (i < n - 1) { // if not all sorted
- counter++; // check while logical condition
- if (names[i].compareTo(names[i + 1]) > 0) {
- // if not correctly ordered then swap names
- String temp = names[i];
- counter++;
- names[i] = names[i + 1];
- counter++;
- names[i + 1] = temp;
- counter++;
- i = 0;
- counter++;// start sorting from the beginning of the array
- } else {
- // now all items until position i in the array is sorted
- i = i + 1;
- counter++;// move to the next position
- }
- counter++; // check if logical condition
- }
- counter++; // check while logical condition
- usifWork = counter;
- }
- public static void main(String[] args) {
- // number of students
- int n = 24;
- // 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 basic operations\n", n,
- aviWork);
- System.out.printf("Usif sorted %d names in %d basic operations\n", n,
- usifWork);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement