I have been following Alex Allain's book to get a very good understanding of C++. I already knew some basics, but I got stuck as I always do on arrays and sorting algorithms. Anyway, one of the problems he presented was to check if an array is sorted or not. And if its not, sort it... Here is the code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
void swap(int array[], int firstindex, int secondindex);
int findsmallel(int array[], int size, int index)
{
int indexofsmall=index;
for(int i=index+1; i<size; i++)
{
if(array[i]<array[indexofsmall])
{
indexofsmall=i;
}
}
return indexofsmall;
}
int findhigh(int array[], int size, int index)
{
int indexofhigh=index;
for(int i=index+1; i<size; i++)
{
if(array[i]>array[indexofhigh])
{
indexofhigh=i;
}
}
return indexofhigh;
}
void sortlow(int array[], int size)
{
for (int i=0; i<size; i++)
{
int index=findsmallel(array, size, i);
swap(array, index, i);
}
}
void sorthigh(int array[], int size)
{
for (int i=0; i<size; i++)
{
int index=findhigh(array, size, i);
swap(array, index, i);
}
}
void swap(int array[], int firstindex, int secondindex)
{
int temp=array[firstindex];
array[firstindex]=array[secondindex];
array[secondindex]=temp;
}
void displayarray(int array[], int size)
{
cout<<"{ ";
for(int i=0; i<size;i++)
{
if(i!=0)
{
cout<<", ";
}
cout<<array[i];
}
cout<<" }";
}
int main()
{
int inputedarray[5];
cin>>inputedarray[];
if(inputedarray[4] != sortlow || inputedarray[4] != sorthigh)
{
sortlow(inputedarray, 5);
displayarray(inputedarray, 5);
}
else
cout<<"Array is already sorted."<<endl;
return 0;
}
Getting two errors about the comparison between a pointer and an integerm when checking the condition. Any help would be greatly appreciated! EDIT: The errors I am getting is: C:\Code Block Projects\Alex Allains Book\Chapter 1\main.cpp|84|error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
And any way to check and see if the arrays are sorted or not? Please? :(
mainwhich makes no sense. Recheck.if(inputedarray[4] != sortlow || inputedarray[4] != sorthigh)?cin>>inputedarray[5];is undefined behavior. You're inputting into the sixth element in the five-element array.