Zombie
Zombie

Reputation: 341

Sorting names by alphabetical order: more efficient way

I'm developing an application and one of the functions is the function sort_books which basically has to sort the name of the books in the file fp by alphabetical order and then writes the books into the file fp2 and prints the names of the books by alphabetical order into the console.

My function is working perfectly with the bubble sort algorithm but to sort 100000 books it tooks approximately 4 minutes, which is way too much time.

Someone knows how I could adapt this code to be way more efficient and quicker?

FILE *fp
FILE *fp2;

sort_books(){
struct book books[100000];
struct book b;

//open files

int i = 0;
while (!feof(fp)){

   fread(&b,sizeof(b),1,fp);

       if(feof(fp))
    {
        break;
    }   

    books[i] = b;
        i++;        
}

//number of books in the file
int len = i;

//bubble sort;
int j = 0;

//Bubble sort: sorting algorithm
    for(i=0; i<len; i++)
    {
        for(j=0; j<len-1; j++)
        {
           //If the first book should come after the next book in the array
           if(strcmp(books[j].name, books[j+1].name) > 0)
        {
            //swap the books
            struct book temp;
            temp = books[j];
            books[j] = books[j+1];
            books[j+1] = temp;
        }
        }
    }

    //now write each book in the array "books" into the file one by one
    int z;
    for(z=0; z<len; z++)
    {   
        fwrite(&books[z],sizeof(books[z]),1,fp2);
        //test console
        printf("Name: %s \n", books[z].name);
    }

    //close files

    }

Upvotes: 0

Views: 5700

Answers (1)

Jobs
Jobs

Reputation: 3377

Bubble sort is O(n^2). You could try Quicksort, which is O(nlogn). Essentially, most sorting algorithms are faster than the bubble sort you demonstrated.

enter image description here

For a list of most common sorting methods, their animations, as well as their implementations, refer to the following page:

http://www.sorting-algorithms.com/

Upvotes: 2

Related Questions