This:
char* title_temp = title_arr[i];
title_arr[j] = title_temp;
Is equivalent to:
title_arr[j] = title_arr[i];
You never swap them, you just copy one to the other. You should add this line:
title_arr[i] = title_arr[j];
In between the two. That way, you'll overwrite [i]
with [j]
, but _temp
still 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) or std::sort
(in C++).
int mystrsort(const void *a, const void *b)
{
return strcmp(*(const char **)a, *(const char **)b);
}
// later:
qsort(title_arr, sizeof title_arr / sizeof(char *), sizeof(char *), mystrsort);
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::sort
example. I'm just not sufficiently familiar with C++.