冒泡排序思想
相邻比较,交换位置
冒泡排序代码
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int nums[6] = {12,21,9,32,6,19};
int len = sizeof(nums) / sizeof(nums[0]);
for(int j = 0; j < len - 1; j++)
{
//i:表示要比较的数的位置
for(int i = 0; i < len - 1; i++)
{
//当前数与后一个数比较
if (nums[i] > nums[i+1])
{
//当前数大于后一个数,交换位置
int x = nums[i];
nums[i] = nums[i+1];
nums[i+1] = x;
}
}
}
for(int i = 0; i < len; i++)
{
cout << nums[i] << ",";
}
cout << endl;
return 0;
}
选择排序思想
寻找最值
,
交换位置
选择排序代码
#include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int nums[] = {65,43,78,91,23,65,76};
// for(int j = 0; j < sizeof(nums) / sizeof(int) -1; j++)
// {
// //记录目标位置
// int toIndex = j;
// //记录最小值下标的位置
// int minIndex = toIndex;
// //比较范围时目标位置~数组长度-1
// for(int i = toIndex; i < sizeof(nums) / sizeof(nums[0]); i++)
// {
// if(nums[minIndex] > nums[i])
// {
// minIndex = i;
// }
// }
// //此时minindex就是查找范围内的最小值下标
// //当查找的最小值位置不是目标位置,才需交换位置
// if(minIndex != toIndex)
// {
// //A:nums[minIndex]
// //B:nums[toIndex]
// int x = nums[minIndex];
// nums[minIndex] = nums[toIndex];
// nums[toIndex] = x;
// }
// }
//j:及时轮巡的次数也是目标位置的下标
for(int j = 0; j < sizeof(nums) / sizeof(int) -1; j++)
{
//记录最小值下标的位置
int minIndex = j;
//比较范围时目标位置~数组长度-1
for(int i = j; i < sizeof(nums) / sizeof(nums[0]); i++)
{
if(nums[minIndex] > nums[i])
{
minIndex = i;
}
}
//此时minindex就是查找范围内的最小值下标
//当查找的最小值位置不是目标位置,才需交换位置
if(minIndex != j)
{
//A:nums[minIndex]
//B:nums[toIndex]
int x = nums[minIndex];
nums[minIndex] = nums[j];
nums[j] = x;
}
}
for(int i = 0; i < sizeof(nums)/ sizeof(int); i++)
{
cout << nums[i] << ",";
}
cout << endl;
return 0;
}