Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function for Alphanumberic Sorting of An Array of Character Arrays

Status
Not open for further replies.

ghostsurfer

Programmer
Aug 10, 2000
8
0
0
US
Does anyone know of a *good* function that will sort an array of charcter arrays alphanumerically and return a pointer to the sorted array.&nbsp;&nbsp;Such as sorting <br>char *fruits[6] { &quot;Oranges&quot;, &quot;Pears&quot;, &quot;Apples&quot;, &quot;Bananas&quot;, &quot;Appricots&quot;, NULL }; <br>Hopefully something like this:<br>char **alpha_sort(char **p_str_arr)<br>{<br>&nbsp;&nbsp;char ** sorted_arr;<br>&nbsp;&nbsp;/* lines of code */<br>&nbsp;&nbsp;return(sorted_arr);<br>}<br>Before I write my own I figure someone must have wanted to do this before and it's probably in some header files, but my pile of C/C++ books is not accessable to me at the moment.<br><br>Thanks!
 
Never mind :) I broke down and wrote one anyway...<br>I'm in a sharing mood:<br><br>char **alpha_sort(char **p_str_arr)<br>{<br><br> // local variables<br> int arr_size;<br> int x;<br> int y;<br> int moved;<br> int i;<br> char *temp;<br><br> // find size of array<br> arr_size = 0;<br> while (p_str_arr[arr_size] != NULL)<br> {<br> arr_size ++;<br> }<br><br> // loop through array<br> x = 0;<br> while (x &lt; arr_size)<br> {<br> // create a flag for moved elements<br> moved = 0;<br> y = 0;<br><br> while (y &lt; arr_size)<br> {<br> // do comparison<br> i = strcmp(p_str_arr[x], p_str_arr[y]);<br> // if in wrong order move elements<br> if (i &lt; 0)<br> {<br> temp = strdup(p_str_arr[x]);<br> p_str_arr[x] = p_str_arr[y];<br> p_str_arr[y] = temp;<br> // set moved flag to true<br> moved = 1;<br> }<br> // increment inner loop<br> y++;<br> } <br> <br> // if we moved nothing, increment outer loop<br> // else we'll see if same element needs to be moved farther<br> if (moved == 0)<br> x++;<br> }<br><br><br> // return pointer to sorted array<br> return (p_str_arr);<br>}<br>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top