Feedjit

Articles for you

Tuesday, December 31, 2013

C++ Program of Implementation of Selection Sort in C++, C Plus Plus,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
 #include <stdlib.h>
  
 void swap(int *x,int *y)
 {
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
 }
  
 void selection_sort(int list[], int n)
 {
   int i, j, min;
   
   for (i = 0; i < n - 1; i++)
   {
     min = i;
     for (j = i+1; j < n; j++)
     {
        if (list[j] < list[min])
        {         
           min = j;
        }
     }
     swap(&list[i], &list[min]);
   }
 }
  
 void printlist(int list[],int n)
 {
    int i;
    for(i=0;i<n;i++)
       printf("%d\t",list[i]);
 }
  
void main()
 {
    const int MAX_ELEMENTS = 10;
    int list[MAX_ELEMENTS];
  
    int i = 0;
     
    // generate random numbers and fill them to the list
    for(i = 0; i < MAX_ELEMENTS; i++ ){
        list[i] = rand();
    }
    printf("The list before sorting is:\n");
    printlist(list,MAX_ELEMENTS);
     
    // sort the list
    selection_sort(list,MAX_ELEMENTS);
  
    // print the result
    printf("The list after sorting:\n");
    printlist(list,MAX_ELEMENTS);
}

Read More

Articles for you