C++中的选择排序
Selection Sort in c++
我试图从这个视频中理解选择排序:
https://www.youtube.com/watch?v=79AB11J5BqU
这是我当前的代码:
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
我是不是像视频一样在做选择排序?
还是我改为做 buble 排序?
谢谢
在选择排序中,您找到一个最小(或最大)元素并将其放在顶部(底部),然后对列表的其余部分再次重复。
这将是一种选择排序,但您不需要交换您比较的每个数字以找到最小的数字。在每个内部循环中存储最小数字索引,并在它结束时进行一次交换。
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
选择排序算法通过从未排序的部分中反复查找最小元素(考虑升序)并将其放在开头来对数组进行排序。
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}
我试图从这个视频中理解选择排序: https://www.youtube.com/watch?v=79AB11J5BqU
这是我当前的代码:
#include <iostream>
int main() {
int numbers[5]={5,3,4,1,2};
int temp;
std::cout<<"BEFORE SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
for (int i = 0; i < 5; ++i) {
for (int j = i+1; j < 5; ++j) {
if(numbers[j]<numbers[i]){
temp = numbers[j];
numbers[j] = numbers[i];
numbers[i] = temp;
}
}
}
std::cout<<"\n\nAFTER SORT : \n";
for(int x=0;x<5;x++){
std::cout<<numbers[x]<<" ";
}
}
我是不是像视频一样在做选择排序? 还是我改为做 buble 排序?
谢谢
在选择排序中,您找到一个最小(或最大)元素并将其放在顶部(底部),然后对列表的其余部分再次重复。
这将是一种选择排序,但您不需要交换您比较的每个数字以找到最小的数字。在每个内部循环中存储最小数字索引,并在它结束时进行一次交换。
unsigned minIndex;
for (int i = 0; i < 5; ++i) {
minIndex = i;
for (int j = i + 1; j < 5; ++j) {
if(numbers[j] < numbers[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { // Do swapping
temp = numbers[i];
numbers[i] = numbers[minIndex];
numbers[minIndex] = temp;
}
}
选择排序算法通过从未排序的部分中反复查找最小元素(考虑升序)并将其放在开头来对数组进行排序。
#include<iostream>
using namespace std;
// Selection Sort//
void Selection_Sort(int a[],int n)
{
for(int i=0;i<n-1;i++)
{
int min_index=i;
for(int j=i;j<n-1;j++)
{
if(a[j]<a[min_index]){
min_index=j;
}
}
swap(a[i],a[min_index]);
}
}
int main()
{
int n,key;
cin>>n;
int a[1000];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
Selection_Sort(a,n);
for(int i=0;i<n;i++)
{
cout<<a[i];
}
}