This program should detect if an array of values (here 5 values of the user's choice) is sorted and if it's not then it should sort it. The problem is my "detection" function sorts every array and I can't figure out why. The logic looks sound to me. Please help.
Code:
#include <iostream>
using namespace std;
int findSmallestValue (int array [], int size, int index)
{
int indexSmallest = index;
for (int i = index + 1; i < size; i++)
{
if (array [i] < array [indexSmallest])
{
indexSmallest = i;
}
}
return indexSmallest; // finds under what index is the smallest value
}
int swap (int array [], int first_index, int second_index)
{
int temp = array [first_index];
array [first_index] = array [second_index];
array [second_index] = temp;
}
void InsertionSort (int array [], int size)
{
for (int i = 0; i < size; i++)
{
int index = findSmallestValue(array, size, i);
swap (array, i, index);
} // This function does the sorting
}
void DisplayArray (int array [], int size)
{ // displays the array nicely
cout << "{";
for (int i = 0; i < size; i++)
{
if (i != 0)
{
cout << ",";
}
cout << array [i];
}
cout << "} \n";
}
bool IsSorted (int array [], int size)
{ // should detect is an array is sorted or not
int index;
for (int i = 0; i < size; i++)
{
index = findSmallestValue(array, size, i);
}
if (index != 0)
{
return false;
}
else if (index = 0)
{
for (int i = index + 1; i < size; i++)
{
index = findSmallestValue(array, size, i);
if (index = i)
{
return true;
}
else
{
return false;
}
}
}
}
int main()
{
int Values [5];
cout << "Enter 5 values of your choice: \n";
for (int i = 0; i < 5; i++)
{
cin >> Values [i];
}
cout << "Your array looks like this: ";
DisplayArray(Values, 5);
if (IsSorted(Values, 5))
{
cout << "Your array is already nicely sorted. \n";
}
else
{
cout << "Your array isn't sorted, let me help you: \n";
InsertionSort(Values, 5);
DisplayArray (Values, 5);
}
}