我如何实现冒泡排序和在哪里

时间:2014-10-09 12:44:06

标签: c++ bubble-sort

任务是实现一个bubblesort函数,然后在我的“familj”数组中使用linearsearch又名“linsok”。数组保持名称和年龄,所以我想在它们的年龄后对数组进行排序并将其打印出来。我有线搜索工作,但现在我坚持使用bubblesort。

问题是我不知道如何使我的冒泡排序代码适用于此代码。 所以我实现了第二段代码吗?

#include <iostream>
#include <string>
using namespace std;



class Person        
{
    public:
    string namn;    
    int alder;

    void skrivUt(string _namn, int _alder)  
    {
        namn = _namn;
        alder = _alder;
    }
};

int linsok(Person* PersonArray, int key) 
{
    for (int i = 0; i < 4; i++)
    {
    if (PersonArray[i].alder == key)
        return i;
    }
return -1;
}


int main()
{

    Person familj[4];               
    familj[1].skrivUt("Emma",23);
    familj[3].skrivUt("Emilia",29);
    familj[2].skrivUt("Johan",26);
    familj[0].skrivUt("Timmy ",21);


int index = linsok(familj,22);  //the age of the person im looking for.


if(index== -1)                      
    cout << "Personen hittades ej!"; //person not found
else            
         //prints out the persons name and the index.                   
    cout << "Personen heter " << familj[index].namn << " hen finns på index " << index << endl;


cin.get();
return 0;
}

这是我之前使用的泡泡排序代码,它起作用。

int p [] = {10,56,73,23,31,24,43};  
int a = 6;


for (int i = 0; i < a; i++)
{
    int nrLeft = a - i;
    for (int j = 0; j < nrLeft; j++)
    {
        if (p[j] > p[j+1])
        {
            int temp = p[j];
            p[j] = p[j+1];
            p[j+ 1] = temp;
        }
    }
}
for(int i = 0; i < 7; i++)
cout << p[i] << endl;  
cin.get();

1 个答案:

答案 0 :(得分:0)

您可能希望将此转换为将Person对象数组传递给它的函数及其大小,然后您只需访问要比较的部分。由于您将其作为函数实现,因此您可以像使用linsok函数一样使用它,尽管您可能希望它返回已排序的数组而不是索引。 以下代码的免责声明:既不运行也不编译

Person* bubbleSort(Person* p, int size)
{
for (int i = 0; i < size; i++)
{
    int nrLeft = size - i;
    for (int j = 0; j < nrLeft; j++)
    {
        if (p[j].alder > p[j+1].alder)
        {
            Person temp = p[j];
            p[j] = p[j+1];
            p[j+ 1] = temp;
        }
    }
}
return p;
}

这是基于你用桤木排序它们(我猜是年龄?我不会说瑞典语(?))你只需要提供签名,并根据你的需要改变它,但基本的想法是您只需更改您比较的内容和数据类型。

另一种方法是返回intvoid(但是你应该返回一个int来告诉你它是否成功),并传递一个指向数组的指针,所以签名中Person**,并直接在该数组上运行,但这有点困难,可以说是不好的做法,具体取决于用例。

相关问题