Advertisement
Guest User

C - Selectionsort - Working

a guest
Apr 12th, 2012
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main(char** argc, int argv ) {
  4.   /*
  5.    * Setting up an array
  6.    */
  7.   int arraylen = 1024;
  8.   int array[arraylen];
  9.   /* Add rendom numbers to it */
  10.   int i = 0;
  11.   while(i < arraylen) {
  12.     array[i] = rand() % 1024;
  13.     i = i + 1;
  14.   }
  15.   /* reset i */
  16.   i = 0;
  17.  
  18.   /* print array*/
  19.   while(i < arraylen) {
  20.     printf("%i: %i \n", i, array[i]);
  21.     i = i + 1;
  22.   }
  23.  
  24.   printf("now sorting...\n");
  25.  
  26.   /* reset i again */
  27.   i = 0;
  28.   /* outer loop */
  29.   while ( i < arraylen ) {
  30.     int j = i + 1; /* set j to i + 1 */
  31.     int indexOfLastLow = i;
  32.     int lastLowValue = array[i];
  33.     /* inner loop */
  34.     printf("---------- outer loop ------\n");
  35.     while ( j < arraylen ) {
  36.       printf("---------- inner loop ------\n");
  37.       if( array[j] < lastLowValue ) {
  38.           printf("new last low new: %i, old was: %i \n",array[j], lastLowValue);
  39.         lastLowValue = array[j];
  40.         indexOfLastLow = j;
  41.       }
  42.       j = j + 1;
  43.     }
  44.     /* Swaping elements */
  45.     int tmp1 = array[i];
  46.     int tmp2 = array[indexOfLastLow];
  47.    
  48.     array[i] = tmp2;
  49.     array[indexOfLastLow] = tmp1;
  50.    
  51.     i = i + 1;
  52.   }
  53.  
  54.   /* reset i */
  55.   i = 0;
  56.  
  57.  
  58.   /* print array*/
  59.   while(i < arraylen) {
  60.     printf("%i: %i \n", i, array[i]);
  61.     i = i + 1;
  62.   }
  63.   return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement