选择排序,及运算复重载

选择排序

思路:遍历数组,每一趟选择最小的数(指针j),和前面(指针i)交换

在这里插入图片描述

1.C++实现:

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[i], arr[minIndex]);
	}
}

对对象进行排序

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

void main(){
    Student d[4] = { { "张三",90}, {"李四",100},{"王五",54} };
    selectionSort(d, 4);
    for (int i = 0; i < 4; i++) {
        cout << d[i];
    }
}

2.python实现:

实现方式一:
def selectionSort(lst):
    for i in range(len(lst)):
        min_index = i
        for j in range(i + 1, len(lst)):
            if lst[j] < lst[min_index]:
                min_index = j
        lst[i], lst[min_index] = lst[min_index], lst[i]
 
实现方式二:
def selectionSort2(lst):
    for i in range(len(lst)):
        min_index = lst.index(min(lst[i:]))
        lst[i], lst[min_index] = lst[min_index], lst[i]

对对象进行排序

class Student:
    def __init__(self,name,score):
        self.name=name
        self.score=score
    def __lt__(self, other):
        return self.score<other.score
    def __str__(self):
        return f'[{self.name},{self.score}]'


if __name__ == '__main__':
    students = [Student("小王",12),Student('小红',6),Student("小黑",2),Student('小灰',11)]
    selectionSort(students)
    for student in students:
        print(student)

3.golang实现:

func selectionSort(slice []int) {
	var minIndex, i, j int
	for i = 0; i < len(slice); i++ {
		minIndex = i
		for j = i + 1; j < len(slice); j++ {
			if slice[j] < slice[minIndex] {
				minIndex = j
			}
		}
		slice[i], slice[minIndex] = slice[minIndex], slice[i]
	}
}

GoLang不支持运算符重载,所以不能直接对结构体进行排序,但可以使用sort.Sort 实现以下三个接口,对结构体数组/切片进行排序:

type Interface interface {
    // Len方法返回集合中的元素个数
    Len() int
    // Less方法报告索引i的元素是否比索引j的元素小
    Less(i, j int) bool
    // Swap方法交换索引i和j的两个元素
    Swap(i, j int)
}
type Student struct {
	Name  string
	Score float32
}
type StudentSlice []Student // 声明一个student的切片类型
func (s StudentSlice) Len() int {
	return len(s)
}
func (s StudentSlice) Less(i, j int) bool {
	return s[i].Score >= s[j].Score // 决定顺序 还是倒序
}
func (s StudentSlice) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func main() {
	var students StudentSlice
	students = append(students, Student{"张三", 69.2})
	students = append(students, Student{"李四", 40.3})
	students = append(students, Student{"王五", 11.2})
	sort.Sort(students)
	fmt.Println(students)
}

选择排序为不稳定排序(如[6, 8, 6, 2],第一遍循环,第一个6和2交换位置),时间复杂度为 O(n^2)

欢迎关注公众号:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值