0

我正在编写一个排序程序,它需要一个数组,用 1000 个随机数填充它,然后将数组复制到第二个数组中。之后程序应该使用 selectionSort 函数和 insertSort 函数。

但是当我使用这些函数时,我应该跟踪所有的交换和关键比较。我已经想出了如何为 insertSort 做到这一点。我无法弄清楚如何为 selectionSort 执行此操作

这是我的代码:

 template <class elemType>
 void selectionSort(elemType list[], int length)
 {
    int loc, minIndex;
int swaps =0;

  for (loc = 0; loc < length; loc++)
  {
    minIndex = minLocation(list, loc, length - 1);

    swap(list, loc, minIndex);

   }
cout<<"swaps = "<<swaps<<endl;
  } //end selectionSort

 template <class elemType>
 void swap(elemType list[], int first, int second)
 {
 elemType temp;
  temp = list[first];
  list[first] = list[second];
  list[second] = temp;
  } //end swap

 template <class elemType>
 int minLocation(elemType list[], int first, int last)
 {
  int loc, minIndex;    
  minIndex = first;

  for (loc = first + 1; loc <= last; loc++)
   { if (list[loc] < list[minIndex])
        minIndex = loc;

}

   return minIndex;
  } //end minLocation

  template <class elemType>
  void insertionSort(elemType list[], int length)
   {
int swaps = 0;
int comp = 0;

   for (int firstOutOfOrder = 1; firstOutOfOrder < length;
                             firstOutOfOrder++)
    if (list[firstOutOfOrder] < list[firstOutOfOrder - 1])
    {
        elemType temp = list[firstOutOfOrder];
        int location = firstOutOfOrder;

        do
        {
            list[location] = list[location - 1];
            location--;
            comp +=1;   
        } while(location > 0 && list[location - 1] > temp);

        list[location] = temp;
         swaps +=1;
    }

cout<<"swaps = "<<swaps<<endl;
cout<<"comps = "<<comp<<endl;
   } //end insertionSort

 #include<iostream>
 #include <ctime>
 #include <cstdlib>
 #include "searchSortAlgorithms.h"

 using namespace std;

 int main (){
//generate a new random set each time 

srand(time(0));

int a[1000] = {0};
int b[1000] = {0};

for(int i= 0; i<1000; i++)
{
    a[i] = rand()% 1000;
    b[i] = a[i];
}


insertionSort(a, 1000);
selectionSort(b, 1000);

    return 0;
 }

为 inertionSort 打印出交换和比较,但我不熟悉如何让它与 selectionSort 一起工作,因为排序算法在 for 循环中调用其他函数。任何输入将不胜感激。

4

1 回答 1

2

实际上,您的选择排序具有固定数量的比较(length * (length-1) / 2)和交换(length)

如果你无论如何都想计算它们,

 // Count variables can be defined in main(), and passed through
 // to swap(), minLocation().
 template <class elemType>
 void swap(elemType list[], int first, int second)
 {
    // Count swap here  
 }

 template <class elemType>
 int minLocation(elemType list[], int first, int last)
 {
   ..
   for (loc = first + 1; loc <= last; loc++)
   { 
      // Count comparation here
   }   
   ..
 }

顺便说一句,您在插入排序中的比较计数也不完整。

for (int firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++)
{    
   // You miss the count here.
   if (list[firstOutOfOrder] < list[firstOutOfOrder - 1])
于 2012-10-24T00:32:30.843 回答