How should I use the qsort function?

This is a discussion on How should I use the qsort function? within the C++ Programming forums, part of the General Programming Boards category; Please tell me ho to use the qsort function. A listing would be nice....

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    How should I use the qsort function?

    Please tell me ho to use the qsort function. A listing would be nice.

  2. #2
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    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;
    }
    zen

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    8

    Talking

    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?

  4. #4
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You'll have to modify the compare function to call strcmp()- in <cstring> -

    Code:
    int compare(const void* first, const void* second)
    {
    	return strcmp(((book*)first)->books,((book*)second)->books);
    
    }
    assuming your struct has a books[30] member.
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 09:28 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07:54 PM
  3. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21