Java:将随机生成的数字克隆或复制到排序方法中,并计算比较和交换的数量

时间:2015-03-15 20:02:23

标签: java sorting random

import java.util.ArrayList;
import java.util.Random;


public class Sorting
{
   public static int numOfComps = 0,  // Number of comparisons
                     numOfSwaps = 0;  // Number of swaps

   public static void main(String[] args)
   {
      System.out.println("\n\nSelection Sort:");
      System.out.println("\n\nQuick Sort:");

      System.out.println("\nOriginal order:\n");
      int size = 5;

      ArrayList<Integer> list = new ArrayList<Integer>(size);

      for(int i = 1; i <= size; i++)
      {
         list.add(i);
      }

      Random rand = new Random();
      while(list.size() > 0)
      {
         int index = rand.nextInt(list.size());
         System.out.print(list.remove(index) + " ");
      }
      //Sort the array
      selectionSort(list);
      quickSort(list);

      System.out.println("\nSorted order: ");
      System.out.print(list + " ");
   }

   public static void selectionSort(int[] array)
   {
      int startScan;   // Starting position of the scan
      int index;       // To hold a subscript value
      int minIndex;    // Element with smallest value in the scan
      int minValue;    // The smallest value found in the scan

      // The outer loop iterates once for each element in the
      // array. The startScan variable marks the position where
      // the scan should begin.
      for (startScan = 0; startScan < (array.length-1); startScan++)
      {
         // Assume the first element in the scannable area
         // is the smallest value.
         minIndex = startScan;
         minValue = array[startScan];

         // Scan the array, starting at the 2nd element in
         // the scannable area. We are looking for the smallest
         // value in the scannable area. 
         for(index = startScan + 1; index < array.length; index++)
         {
            if (array[index] < minValue)
            {
               minValue = array[index];
               minIndex = index;

               numOfSwaps ++;
            }
            numOfComps ++;    //get 15 comparisons here
         }

         // Swap the element with the smallest value 
         // with the first element in the scannable area.
         array[minIndex] = array[startScan];
         array[startScan] = minValue;

         //numOfComps ++;    // Get 5 comparisons here
      }
       System.out.println("\n\nNumber of comps = " + numOfComps);
       System.out.println("Number of swaps = " + numOfSwaps);
    }

    public static void quickSort(int array[])
    {
      doQuickSort(array, 0, array.length - 1);
      System.out.println("\n\nNumber of comps = " + numOfComps);
       System.out.println("Number of swaps = " + numOfSwaps);
    }

    /**
      The doQuickSort method uses the QuickSort algorithm
      to sort an int array.
      @param array The array to sort.
      @param start The starting subscript of the list to sort
      @param end The ending subscript of the list to sort
    */

    private static void doQuickSort(int array[], int start, int end)
    {
       int pivotPoint;

       if (start < end)
       {
          numOfComps++;

          // Get the pivot point.
          pivotPoint = partition(array, start, end);

          // Sort the first sub list.
          doQuickSort(array, start, pivotPoint - 1);

          // Sort the second sub list.
          doQuickSort(array, pivotPoint + 1, end);
       }
    }

    /**
      The partiton method selects a pivot value in an array
      and arranges the array into two sub lists. All the
      values less than the pivot will be stored in the left
      sub list and all the values greater than or equal to
      the pivot will be stored in the right sub list.
      @param array The array to partition.
      @param start The starting subscript of the area to partition.
      @param end The ending subscript of the area to partition.
      @return The subscript of the pivot value.
    */

    private static int partition(int array[], int start, int end)
    {
      int pivotValue;    // To hold the pivot value
      int endOfLeftList; // Last element in the left sub list.
      int mid;           // To hold the mid-point subscript

      // Find the subscript of the middle element.
      // This will be our pivot value.
      mid = (start + end) / 2;

      // Swap the middle element with the first element.
      // This moves the pivot value to the start of 
      // the list.
      swap(array, start, mid);

      // Save the pivot value for comparisons.
      pivotValue = array[start];

      // For now, the end of the left sub list is
      // the first element.
      endOfLeftList = start;

      // Scan the entire list and move any values that
      // are less than the pivot value to the left
      // sub list.
      for (int scan = start + 1; scan <= end; scan++)
      {

         if (array[scan] < pivotValue)
         {
            endOfLeftList++;
            swap(array, endOfLeftList, scan);

                //numOfSwaps ++;
         }
         numOfComps++;
       }

      // Move the pivot value to end of the
      // left sub list.
      swap(array, start, endOfLeftList);

      // Return the subscript of the pivot value.
      return endOfLeftList;
    }

    /**
      The swap method swaps the contents of two elements
      in an int array.
      @param The array containing the two elements.
      @param a The subscript of the first element.
      @param b The subscript of the second element.
    */

    private static void swap(int[] array, int a, int b)
    {
      int temp;

      temp = array[a];
      array[a] = array[b];
      array[b] = temp;
      numOfSwaps++;
    }
}

如何将随机生成的数字克隆或复制到Selection Sort和Quicksort方法,以便两种排序方法具有相同的随机生成数字?我是否正确地将比较次数和交换代码数量放入每种排序方法中?此外,我正在尝试设置输出,以便分拣机名称下的每个排序方法(即选择排序)显示随机生成的数字的原始顺序,比较的数量,交换的数量以及数字的排序顺序。我该如何编码输出?还有一件事,当我运行代码时,我得到一个编译错误,声明所需的参数是sort方法的“int []”,但是找到了“ArrayList”。我该如何解决?我在Google上彻底搜索了这些答案但无济于事。请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

根据第一个列表创建第二个列表:

  ArrayList<Integer> list = new ArrayList<Integer>(size);
  // fill list
  ArrayList<Integer> list2 = new ArrayList<Integer>(list); // pass the first list in

然后将每个列表传递给相应的排序方法,并打印出每个列表:

  //Sort the LIST
  selectionSort(list);
  quickSort(list2);

  System.out.println("\nSorted order: ");
  System.out.print(list + " ");
  System.out.print(list2 + " ");

您可能希望选择比listlist2更好的名称。如果两个列表都正确排序,您将能够更好地判断您是否具有正确的比较和交换次数。


解决您提出的一些问题:

  1. 您可以通过创建字段int numSwaps来计算掉期,每次开始排序时将其设置为0,并在每次交换时将其递增numSwaps++。同样可以进行比较。
  2. 您可以通过编写System.out.println(Arrays.toString(yourArray));
  3. 来打印数组
  4. 要摆脱那个编译错误,在传入之前将ArrayList转换为数组:quickSort(list.toArray(new Integer[list.size()]));