排序算法系列目录
排序算法第一讲 — 冒泡排序(Python、C++、C)
排序算法第二讲 — 选择排序(Python、C++、C)
排序算法第三讲 — 插入排序(Python、C++、C)
排序算法第四讲 — 快速排序(Python、C++、C)
排序算法第五讲 — 希尔排序(Python、C++、C)
排序算法第六讲 — 归并排序(Python、C++、C)
题目描述:
给你一个整数数组 nums,请你将该数组采用选择排序方式进行升序排列。
解题思路:
选择排序的工作原理:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。
代码:
Python写法:
class Solution(object):
def solution(self, nums):
n = len(nums)
j = 0
for i in range(n):
j = i
for j in range(n-i-1):
if nums[j] > nums[j+1]:
temp = nums[j]
nums[j] = nums[j+1]
nums[j+1] = temp
return nums
上面的这个代码,看起来实在是别扭。原因有两点:1. 变量指代不清 2. 逻辑关系不明
import random
def choice(nums):
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i] > nums[j]:
nums[i], nums[j] = nums[j], nums[i]
return nums
nums = [random.randint(0, 10) for i in range(10)]
print(nums)
print(choice(nums))
C++写法:
#include<iostream>
using namespace std;
void swap(int *a, int *b); //交换两个数
int main()
{
int str[5];
int i, j;
for (i = 0; i < 5; i++)
cin >> str[i];
for (i = 0; i < 5; i++)
{
j = i;
for (j = 0; j < 5 - i - 1; j++)
{
if (str[j] > str[j + 1])
{
swap(&str[j], &str[j + 1]);
}
}
}
for (i = 0; i < 5; i++)
cout << str[i] <<" ";
printf("\n");
return 0;
}
void swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
C语言:
#include <stdio.h>
void swap(int *a, int *b); //交换两个数
int main()
{
int str[5];
int i, j;
for (i = 0; i < 5; i++)
scanf("%d", &str[i]);
for (i = 0; i < 5; i++)
{
j = i;
for (j = 0; j < 5 - i - 1; j++)
{
if (str[j] > str[j + 1])
{
swap(&str[j], &str[j + 1]);
}
}
}
for (i = 0; i < 5; i++)
printf("%d ", str[i]);
printf("\n");
return 0;
}
void swap(int *a, int *b)
{
int c;
c = *a;
*a = *b;
*b = c;
}
题目来源: