簡體   English   中英

跟蹤掉期和比較

[英]Keep track of swaps and comparisons

我正在編寫一個需要取一個數組的排序程序,用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,因為sort算法調用for循環中的其他函數。 任何輸入將不勝感激。

實際上,您的選擇排序具有固定數量的比較(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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM