虽然我非常确定其他一切的位置交换次数是正确的,但我的InsertionSort函数的位置交换次数显示为零。
我不确定为什么。
有关如何解决此逻辑错误的任何想法?
#include <iostream>
using namespace std;
const int SIZE=20;
void bubbleSort(int numbers[], int SIZE);
void selectionSort(int numbers[], int SIZE);
void insertionSort(int numbers[], int SIZE, int &a, int &b);
int main()
{
int numbers[SIZE]= {26, 45, 56, 12, 78, 74, 39, 22, 5, 90, 87, 32, 28, 11, 93, 62, 79, 53, 22, 51};
int value=0;
bool found;
int a;
int b;
cout << "Today we are going to be searching for values." << endl;
cout << "These are the values you have to choose from" << endl;
for (int i=0; i<SIZE; i++)
cout << numbers[i]<<"; ";
do
{
cout << "Make sure to enter a value that's in the list." << endl;
cin >> value;
found=false;
for (int i=0; i<SIZE; i++)
{
if (value==numbers[i])
{
found=true;
break;
}
}
if (!found)
cout << "Enter a valid value !" << endl;
}
while (!found);
bubbleSort(numbers, SIZE);
selectionSort(numbers, SIZE);
insertionSort(numbers, SIZE, a, b);
return 0;
}
void bubbleSort (int numbers[], int SIZE)
{
cout<<"\nOriginal order: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
int maxElement;
int index,counter=0;
for(maxElement=SIZE-1; maxElement>=0; maxElement--)
{
for(index=0;index<=maxElement-1;index++)
{
if(numbers[index]>numbers[index+1])
{
swap(numbers[index], numbers[index+1]);
counter++;//increments counter everytime swap occurs
}
}
}
cout<<"\nBubble Sorted: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
cout<<"\nNumbers of location swap: "<<counter<<endl;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
void selectionSort(int numbers[], int SIZE)
{ cout<<"\nOriginal order: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
int startScan;
int index;
int miniIndex;
int miniValue;
int counter=0;
for(startScan=0;startScan<(SIZE-1);startScan++)
{
miniIndex=startScan;
miniValue=numbers[startScan];
for(index=startScan+1;index<SIZE;index++)
{
if(numbers[index]<miniValue)
{
miniValue=numbers[index];
miniIndex=index;
}
}
swap(numbers[miniIndex], numbers[startScan]);
counter++;
}
cout<<"\nSelection Sorted: ";
for(int i=0;i<SIZE;i++)
cout<<numbers[i]<<' ';
cout<<"\nNumbers of location swap: "<<counter<<endl;
cout << endl;
}
void insertionSort(int numbers[], int SIZE, int &a, int &b)
{
int temp = a; a = b; b = temp;
int j, swap = 0;
cout<<"Original order: ";
for(int i = 0; i < SIZE; i++)
cout<< numbers[i] << ' ';
for (int i = 0; i < SIZE; i++){
j = i;
while (j > 0 && numbers[j] < numbers[j-1])
{
temp = numbers[j];
numbers[j] = numbers[j-1];
numbers[j-1] = temp;
j--; swap++;
}
}
cout <<"\nThe number of location swaps is: "<< swap << endl;
return;
}
答案 0 :(得分:2)
您为插入排序获得了0次交换,因为插入排序执行了0次交换,因为数组已经排序,因为您之前对它进行了冒泡排序。
如果N是数组的大小,即使数组已经排序,你的选择排序函数总是执行N-1交换,因此你没有得到0个交换选择排序。
对于冒泡排序,您没有获得0个交换,因为此时数组尚未排序。