Day 4_3 initial algorithm - sort (simple application)

1. Bubble Sort

Mainly the exchange position, the number of array starts from the first comparator, to determine the maximum number, and finally into an array, the second largest in the determination of the number, and so on, is forward from the back row. Previous article have code examples

2. Select Sort

Enumeration, find the smallest number from the sequence, with the first switching element, the n-1 remaining ordered sequence is to be continued from the n-1 to find the smallest, and the second switching element, the remaining n-2 th sequence is to be sorted, and so on.

#include<cstdio>
#include<cstring>
void selectSort(int A[],int n){
	for(int i = 0;i<n;i++){
		int k = i;
		for(int j = i;j<n;j++){
			if(A[j] < A[k])
				k = j; 
		}
		int temp = A[i];
		A[i] = A[k];
		A[k] = temp;
	}
}
int main(){
	int a[] = {1,5,4,8,9,3,2,10,7,6};
	int len = sizeof(a)/sizeof(int);
	selectSort(a,len);
	for(int i = 0;i<len;i++)
		printf("%d ",a[i]); 
	return 0;
} 

3. Insertion Sort

#include<cstdio>
#include<cstring> 
void selectSort(int A[],int n){
	for(int i = 1;i<n;i++){
		int temp = A[i],j = i;
		while(j>1 && temp<A[j-1]){
			A[j] = A[j-1];
			j--;
		}
		A[j] = temp;
	}
}
int main(){
	int a[] = {1,5,4,8,9,3,2,10,7,6};
	int len = sizeof(a)/sizeof(int);
	selectSort(a,len);
	for(int i = 0;i<len;i++)
		printf("%d ",a[i]); 
	return 0;
} 

4. sort Application Function

Qsort in C language or C ++ in the sort function (recommended)

1.sort function

You must be added to the header file and #include using namespace std;
sort (the first address element, the next element address of the end address, comparison function (optional));

A simple example

#include<cstdio>
#include<algorithm> 
using namespace std;
int main(){
	int a[6] = {9,4,2,5,6,-1};
	sort(a,a+4);	//a[0]到a[3]从小到大排序
	for(int i = 0;i<6;i++)
		printf("%d ",a[i]);
	printf("\n");
	sort(a,a+6);	//a[0]到a[5]从小到大排序
	for(int i = 0;i<6;i++)
		printf("%d ",a[i]);
	return 0;
} 

The same type of double char arrays and array usage

Step 5. common theme sorting

1. The data presented for each plurality of information, such as student structure

First, realize cmp function, press the same fraction of the size of the row, scores of small press lexicographical name row

//对于结构体的比较 
bool cmp(Student a,Student b){
	if(a.score != b.score) return a.score > b.score;
	else return strcmp(a.name,b.name) < 0; 
} 

Achieve rankings (by score in descending sequence has been lined up), the same score occupy the same rank, r attribute indicates the ranking

stu[0].r = 1;
	for(int i = 0;i<n;i++){
		if(stu[i].score == stu[i-1].score){
			stu[i].r = stu[i-1].r;
		}else{
			stu[i].r = i + 1;
		}
	}
Published 26 original articles · won praise 3 · Views 212

Guess you like

Origin blog.csdn.net/qq_41898248/article/details/103758526