Please tell me ho to use the qsort function. A listing would be nice.
Printable View
Please tell me ho to use the qsort function. A listing would be nice.
This'll sort a array of 10 random int's -
Code:#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int compare(const void* first, const void* second)
{
if (*(int*)first<*(int*)second)
return -1;
if (*(int*)first>*(int*)second)
return 1;
return 0;
}
int main()
{
srand((unsigned)time(0));
int array[10];
for(int i=0;i<10;i++)
array[i]=rand()%10000;
qsort(array,sizeof(array)/sizeof(int),sizeof(int),compare);
for(int j=0;j<10;j++)
cout << array[j] << endl;
return 0;
}
Thanks. That worked. Niw, another question. I have the following structure
struct book
{
char name[30];
char book[30];
}b[10];
How can I sort this array by the name of the book using the qsirt function?
You'll have to modify the compare function to call strcmp()- in <cstring> -
assuming your struct has a books[30] member.Code:int compare(const void* first, const void* second)
{
return strcmp(((book*)first)->books,((book*)second)->books);
}