用C++实现冒泡排序

我用C++写了个关于冒泡排序的算法,但是每次输出都把数组原样输出出来了

第1个回答  2021-04-16

给大家介绍冒泡排序的Scratch做法

第2个回答  2019-03-30
第二个for j=i j<i能成立???
并且里面没用到j
for i=O i<b-1
for j=i+1 j<b追问

改了,输出结果更神奇了😂

追答

if(a[i] >a [j])
{

tmp = a[i]
a[i] = a[j]
a[j]=a[i]

}

第3个回答  2019-03-30
if下面的3行需要用{}括起来追问

加了,还是一样的,把原数组输出来来

追答

tem=a[i];
这个也写反了,改吧

追问

追答

如果一定要我说你完全写错了,可能会打击自信心

#include <stdio.h>
#include <iostream.h>

void insertNumber(int a[], int b)
{
for (int i = 0; i < b; i++)
{
for (int j = 0; j < b - i; j++)
{
int tem = 0;
if (a[j] > a[j+1])
{
tem = a[j];
a[j] = a[j+1];
a[j+1] = tem;
}
}
}
for (int n = 0; n < b; n++)
{
cout << a[n] << endl;
}

}

void main()
{
int a[] = {7, 4, 5, 8, 1};
int b = 5;
insertNumber(a, b);

}

本回答被提问者采纳
第4个回答  2019-03-30
1、参考别人的代码也是学习的一种方法,搜索结果第一个就有。
2、代码如下
//
// main.cpp
// BubbleSort
//
// Created by MadMarical on 15/11/19.
// Copyright (c) 2015年 com. All rights reserved.
//

#include <iostream>

using namespace std;

void bubbleSort(int* pData,int length)
{
int temp;
for(int i = 0;i != length;++i)
{
for (int j = 0; j != length; ++j)
{
if (pData[i] < pData[j])
{
temp = pData[i];
pData[i] = pData[j];
pData[j] = temp;
}
}
}
}

void print(int* pData,int length)
{
for (int i = 0; i != length; ++ i)
{
cout<<pData[i]<<" ";
}
cout<<endl;
}

int main(int argc, const char * argv[])
{
int pData[] = {2,3,7,1,6};
BubbleSort(pData,5);

cout<<"the result is:";

print(pData,5);

return 0;
}
相似回答