Skip to content

Commit 2533f02

Browse files
committed
update selection sort
1 parent a6bbb27 commit 2533f02

File tree

2 files changed

+25
-50
lines changed

2 files changed

+25
-50
lines changed

include/selection_sort.h

Lines changed: 20 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,27 @@
1-
#ifndef _selection_sort_h_
2-
#define _selection_sort_h_
1+
#ifndef __SELECTION_SORT_H__
2+
#define __SELECTION_SORT_H__
33

4-
5-
6-
namespace aglo{
7-
4+
namespace alg {
85
template<typename T>
9-
static void SelectionSort(T list[],int start,int end){
10-
11-
int min_index;
12-
T tmp;
13-
14-
if(start < end){
15-
16-
for(size_t i = start; i <= end-1; ++i)
17-
{
18-
min_index=i;
19-
for(size_t j = i+1; j <= end; ++j)
20-
{
21-
if ( list[i] >= list[j])
22-
min_index=j;
23-
24-
}
25-
26-
if (i != min_index)
27-
{
28-
tmp=list[i];
29-
list[i]=list[min_index];
30-
list[min_index]=tmp;
31-
6+
static void SelectionSort(T list[],int start,int end){
7+
int min_index;
8+
T tmp;
9+
if(start < end){
10+
for(size_t i = start; i <= end-1; ++i) {
11+
min_index=i;
12+
for(size_t j = i+1; j <= end; ++j) {
13+
if ( list[i] >= list[j])
14+
min_index=j;
15+
}
16+
17+
if (i != min_index) {
18+
tmp=list[i];
19+
list[i]=list[min_index];
20+
list[min_index]=tmp;
21+
}
3222
}
3323
}
34-
3524
}
36-
37-
38-
39-
}
40-
4125
}
4226

43-
44-
45-
46-
#endif
27+
#endif //__SELECTION_SORT_H__

src/selection_sort_demo.cpp

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
1-
21
#include <stdio.h>
32
#include <stdlib.h>
43
#include <time.h>
54

65
#include "generic.h"
76
#include "selection_sort.h"
87

9-
108
template<typename T>
11-
static void printlist(T & list,int count)
12-
{
9+
static void printlist(T & list,int count) {
1310
int i;
1411
for(i=0;i<count;i++)
1512
printf("%d\t ",list[i]);
1613
printf("\n");
1714
}
1815

1916

20-
int main (int argc, char const *argv[])
21-
{
17+
int main (int argc, char const *argv[]) {
2218
const int MAX_ELEMENTS = 10;
2319
int list[MAX_ELEMENTS];
2420
for(int i = 0; i < MAX_ELEMENTS; i++ ){
@@ -27,12 +23,10 @@ int main (int argc, char const *argv[])
2723
printf("The list before sorting is:\n");
2824
printlist(list,MAX_ELEMENTS);
2925

30-
// sort the list using quicksort
31-
aglo::SelectionSort(list,0,MAX_ELEMENTS-1);
26+
alg::SelectionSort(list,0,MAX_ELEMENTS-1);
3227

33-
// print the result
34-
printf("The list after sorting using quicksort algorithm:\n");
28+
printf("The list after sorting using selection sort algorithm:\n");
3529
printlist(list,MAX_ELEMENTS);
3630

3731
return 0;
38-
}
32+
}

0 commit comments

Comments
 (0)