选择排序

本文深入讲解了选择排序算法的工作原理,包括如何在未排序序列中查找最小元素并将其放置于正确位置,以及算法的复杂度分析。通过示例代码展示了算法实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

选择排序是一种简单直观的排序算法。它的工作原理是:

首先在未排序序列中找到最小元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小元素,放到排序序列的末尾。以此类推,直到所有元素排序完毕

选择排序的交换操作介于0和n-1次之间;比较操作为n(n-1)/2之间;赋值操作介于0和3(n-1)次之间;其平均复杂度为O(n²)

代码如下:

package book;

import java.util.Scanner;

public class JiOu {
	public static void selectSort(int[] source) {
		for (int i = 0; i < source.length; i++) {
			for (int j = i + 1; j < source.length; j++) {
				if (source[i] > source[j]) {
					swap(source, i, j);
				}
			}
		}
	}

	private static void swap(int[] source, int x, int y) {
		int temp = source[x];
		source[x] = source[y];
		source[y] = temp;
	}

	public static void main(String[] args) {
		// int[] a = {4,2,1,6,3,6,0,-5,1,1};
		System.out.println("请输入数组的大小;");
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int[] score = new int[n];
		System.out.println("请输入数组的元素:");
		for (int i = 0; i < score.length; i++) {
			score[i] = sc.nextInt();
		}
		sc.close();
		selectSort(score);
		System.out.println("最终的排序为:");
		for (int i = 0; i < score.length; i++) {
			System.out.print(score[i] + "  ");
		}
	}
}

 

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值