繁体   English   中英

C ++排序问题

[英]C++ Sorting problem

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

如果我(依次输入) 1, 2, 3, 4, 5, 6, 7, 8, 9, 10该代码可以正常工作..但是,如果输入该数字,则无序地将其分解..

我的代码是:

#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;
}

非常感谢...

我想创建一个分类系统

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

http://codepad.org/VBAB0JBo

#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;
}

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

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]
    }
}

如果您使用的是C ++,则可以使用STL std :: vector而不是array,然后使用STL算法std :: sort

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM