首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++排序问题

C++排序问题
EN

Stack Overflow用户
提问于 2011-01-31 04:01:49
回答 3查看 1K关注 0票数 1

我想创建一个排序系统,它获取一些数字并对其进行DESC排序。

如果我输入1, 2, 3, 4, 5, 6, 7, 8, 9, 10 (有序),代码就能正常工作。但是如果无序地输入这些数字,它就会被分解。

我的代码是:

代码语言:javascript
复制
#include <iostream.h>
main () {
 int a[10], max, temp;
 for (int i=0; i<10; i++) {
    cout << "Enter number " << i+1 << ": ";
    cin >> a[i];
 }

 for (int j=0; j<10; j++) {
  for (int x=0; x<=j; x++) {
    if (a[j] > a[j+1]) {
     temp = a[j];
     a[j] = a[j+1];
     a[j+1] = temp;
    }
  }
 }

 cout << "Sort [DESC]: \n";
 for (int w=9; w>=0; w--) {
    cout << w << ". " << a[w] << "\n";
 }
 //cout << "Max: " << max;
}

非常感谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-31 04:06:59

您正在访问a[10] (通过a[j+1]),这肯定是不正确的。简单的冒泡排序通常看起来像这样,例如:

代码语言:javascript
复制
for(int i = NUMBER_OF_ELEMENTS - 1; i > 0; --i)
for(int t = 0; t < i; ++t)
{
    if(item [t] greater than [t+1])
    {
        swap item [t] with [t+1]
    }
}
票数 2
EN

Stack Overflow用户

发布于 2011-01-31 04:10:12

我想创建一个分类系统

作为标准库的一部分,已经为您完成了:

http://codepad.org/VBAB0JBo

代码语言:javascript
复制
#include <algorithm>
#include <iostream>
#include <functional>

void PrintNumbers(int * myArray)
{
    std::copy(myArray, myArray + 10, std::ostream_iterator<int>(std::cout, ","));
    std::cout << std::endl;
}

int main()
{
    int myArray[10] = {1,2,3,4,5,6,7,8,9,10};
    //Sort ascending
    std::sort(myArray, myArray + 10);
    PrintNumbers(myArray);
    //Sort descending
    std::sort(myArray, myArray + 10, std::greater<int>());
    PrintNumbers(myArray);
    return 0;
}
票数 3
EN

Stack Overflow用户

发布于 2011-01-31 04:07:19

如果你使用的是C++,你可以使用STL std::vector代替数组,然后使用STL算法std::sort

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4845155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档