数据结构算法学习总结-慕课网(一)选择排序(从小到大)

数据结构算法学习总结-慕课网(一)选择排序(从小到大)

1.说明

语法采用c++,不懂得可以去学习一下c++的基本语法

2.思路

从小到大,也就是后一个比前一个小的话,那么就把二者的顺序交换

3.时间复杂度计算

时间复杂度,T(n)=O(f(n))

选择排序程序执行的次数,f(n)=n^2,所以时间复杂度为O(n^2)

4.代码

SelectionSort.cpp

#include <iostream>
#include "Student.h"
using namespace std;


/**
 * 选择排序
 */
template<typename T>
void selectionSort(T arr[],int n){
	for(int i = 0;i<n;i++){
		int minIndex = i;
		for(int j = i+1;j<n;j++){
			if(arr[j] < arr[minIndex]){
				minIndex = j;
			}
		}
		swap(arr[minIndex],arr[i]);//把a,b交换位置
	}
}


int main() {
	int arr[5] = {1,20,8,4,3};
	selectionSort(arr,5);
	for(int i = 0;i<5;i++){
		cout << arr[i] << " "; //循环打印int数组中的元素
	}
	cout << endl;


	float b[5] = {1.1,5.3,4.2,0.3,2.5};
	selectionSort(b,5);
	for(int i = 0;i<5;i++){
		cout << b[i] << " "; //循环打印float数组中的元素
	}
	cout << endl;


	string c[5] = {"A","D","B","C","E"};
	selectionSort(c,5);
	for(int i = 0;i<5;i++){
		cout << c[i] << " "; //循环打印string数组中的元素
	}
	cout << endl;


	Student s[5] = {{"A",50},{"D",60},{"B",30},{"E",90},{"C",60}};
	selectionSort(s,5);


	for(int i = 0;i<5;i++){
		cout << s[i] << " ";//循环打印自定义数组中的元素
	}
	cout << endl;




	return 0;
}


Student.h

#ifndef STUDENT_H_
#define STUDENT_H_

#include <iostream>
using namespace std;

struct Student{
	string name;
	int score;
	bool operator<(const Student &otherStudent){
		return score!=otherStudent.score?score<otherStudent.score:name<otherStudent.name;
	}
	friend ostream&operator<<(ostream&os,const Student &student){
		os<<"Student: "<<student.name<<" "<<student.score<<",";
		return os;
	}

};

#endif /* STUDENT_H_ */


猜你喜欢

转载自blog.csdn.net/libinbin147256369/article/details/79950559
今日推荐