C ++ and Java implement basic selection sorting and Common Errors
I. Basic Idea of sorting:
First, find the smallest element in the array, and then swap it with the first element of the array (if the first element is the smallest element, it is exchanged with itself ), find the smallest element in the remaining element and swap it with the second element of the array. This loop continues until the entire array is sorted. This method is called selection sorting.
For an array with a length of N, it takes about N ^ 2/2 comparisons and N exchanges to sort the array.
C ++ code implementation:
# Include <iostream>
Using namespace std;
Template <typename T>
Void selectionSort (T a [], int N ){
For (int I = 0; I <N; I ++ ){
Int min = I;
For (int j = I + 1; j <N; j ++)
If (a [min]> a [j])
Min = j;
Swap (a [I], a [min]);
}
}
Int main (){
Int arr [10] = };
SelectionSort (arr, 10 );
For (int I = 0; I <10; I ++)
Cout <arr [I] <"";
Cout <endl;
System ("pause ");
}
Java code implementation:
Package selectionsort;
Public class SelectionSort {
Public static void selectionSort (Comparable [] ){
Int N = a. length;
For (int I = 0; I <N; I ++ ){
Int min = I;
For (int j = I + 1; j <N; j ++)
If (less (a [j], a [min])
Min = j;
Exch (a, I, min );
}
}
Private static boolean less (Comparable v, Comparable w ){
Return v. compareTo (w) <0;
}
Private static void exch (Comparable [] a, int I, int j ){
Comparable t = a [I]; a [I] = a [j]; a [j] = t;
}
Public static void main (String [] args ){
Integer [] arr = {4, 7, 8, 3, 9, 5, 6, 1, 2 };
SelectionSort. selectionSort (arr );
For (int I = 0; I <arr. length; I ++ ){
System. out. print (arr [I]);
System. out. print ('');
}
}
}
Ii. Common Errors
Problem description: after running the program, the first element and the second element are not sorted in order. For example
Solution: In the code selectionSort method, the if judgment statement should not be nested into the second for loop.
Because the second for loop is used to find the elements in the position where I is exchanged, it is necessary to find the elements in the loop before judging the relationship between it and I.
This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151412.htm