Can you tell me what’s wrong with my method? I ends up putting the same thing everywhre and it’s actually not sorting.
void sortArrays(){
int i, j;
for(i=0; i<counter; i++){
for( j=0; j<i; j++){
if( strcmp(title_arr[i], title_arr[j]) < 0){
char* title_temp = title_arr[i];
title_arr[j] = title_temp;
}
}
}
This:
Is equivalent to:
You never swap them, you just copy one to the other. You should add this line:
In between the two. That way, you’ll overwrite
[i]with[j], but_tempstill holds the old value of[i], so you can copy that value into[j], thus swapping them.I suppose it’s also a time for a lesson on algorithms. Your algorithm is known as a “bubble sort” algorithm. It is known for it’s simplicity, but in a realistic setting it is known for it’s inefficiency (the technical term is “teh sux”, and the real technical term is
O(n^2)(“N squared”) performance). Some more common (and more efficient) algorithms include Quicksort, merge sort, and Heapsort, among many others. For more about measuring algorithmic scalability, see the article on Big Oh notation.*But, as vava pointed out in a comment, unless your assignment is to write your own sorting function, you’re going to get better performance with
qsort(in C) orstd::sort(in C++).I’m not going to stab at
std::sort, but it’s going to work about the same (perhaps easier).***Note that anyone who likes is free to change these Wikipedia links to Stack Overflow links. It would be better to link to SO, I just linked to Wikipedia because I knew how to find the info I needed faster.
**Note that anyone who likes is free to add a
std::sortexample. I’m just not sufficiently familiar with C++.