selection sort program in c code example
Example 1: selection sort in java
public static void SelectionSort(int[] arr)
{
int small;
for (int i = 0; i <arr.length - 1; i++)
{
small = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[small])
{
small = j;
int temp = arr[i];
arr[i] = arr[small];
arr[small] = temp;
}
}
}
}
Example 2: selection sort program in c
#include<stdio.h>
int main(){
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=0;i<count;i++){
for(j=i+1;j<count;j++){
if(number[i]>number[j]){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Example 3: selection sort
def ssort(lst):
for i in range(len(lst)):
for j in range(i+1,len(lst)):
if lst[i]>lst[j]:lst[j],lst[i]=lst[i],lst[j]
return lst
if __name__=='__main__':
lst=[int(i) for i in input('Enter the Numbers: ').split()]
print(ssort(lst))
Example 4: how to send values to a selection sorting function
1
2
3
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include <iomanip>
9 using std::setw;
10
11 void selectionSort( int * const, const int );
12 void swap( int * const, int * const );
13
14 int main()
15 {
16 const int arraySize = 10;
17 int a[ arraySize ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };
18
19 cout << "Data items in original order\n";
20
21 for ( int i = 0; i < arraySize; i++ )
22 cout << setw( 4 ) << a[ i ];
23
24 selectionSort( a, arraySize );
25
26 cout << "\nData items in ascending order\n";
27
28 for ( int j = 0; j < arraySize; j++ )
29 cout << setw( 4 ) << a[ j ];
30
31 cout << endl;
32 return 0;
33 }
34
35
36 void selectionSort( int * const array, const int size )
37 {
38 int smallest;
39
40
41 for ( int i = 0; i < size - 1; i++ )
42 {
43 smallest = i;
44
45
46 for ( int index = i + 1; index < size; index++ )
47
48 if ( array[ index ] < array[ smallest ] )
49 smallest = index;
50
51 swap( &array[ i ], &array[ smallest ] );
52 }
53 }
54
55
56
57 void swap( int * const element1Ptr, int * const element2Ptr )
58 {
59 int hold = *element1Ptr;
60 *element1Ptr = *element2Ptr;
61 *element2Ptr = hold;
62 }