簡體   English   中英

陣列交換陣列

[英]Array swap an Array

編寫一個名為swap的函數,該函數具有void swap(int&,int&)的原型; 交換兩個不按遞增順序排列的鄰居。

這是我到目前為止所擁有的

include <iostream>
using namespace std;
int main()
{
    int array[]={34, 21, 89,56,78,2,14,56,0,99};
    int countComparisons=0;

    cout<<"Original List: ";
    for (int i=0; i<=9; i++) cout<<a[i]<<" "; cout<<endl; //print array
    for (int start=0; start<=9;start++) //outer loop
    {
        for (int i=0; i<9; i++)  //inner loop
        {
            countComparisons++;
            if (array[i]>array[i+1])
            {

        }
    }
    cout<<"\nFinal List: ";
    for (int i=0; i<=9; i++) cout<<a[i]<<" "; cout<<endl; //print array
    cout <<"Number of comparions "<<countComparisons<<endl;
    return 0;
}

輸出是

Original List: 34 21 89 56 78 2 14 56 0 99
swapped 34 with 21
21 34 89 56 78 2 14 56 0 99
swapped 89 with 56
21 34 56 89 78 2 14 56 0 99
swapped 89 with 78
21 34 56 78 89 2 14 56 0 99
swapped 89 with 2
21 34 56 78 2 89 14 56 0 99
swapped 89 with 14
21 34 56 78 2 14 89 56 0 99
swapped 89 with 56
21 34 56 78 2 14 56 89 0 99
swapped 89 with 0
21 34 56 78 2 14 56 0 89 99
swapped 78 with 2
21 34 56 2 78 14 56 0 89 99
swapped 78 with 14
21 34 56 2 14 78 56 0 89 99
swapped 78 with 56
21 34 56 2 14 56 78 0 89 99
swapped 78 with 0
21 34 56 2 14 56 0 78 89 99
swapped 56 with 2
21 34 2 56 14 56 0 78 89 99
swapped 56 with 14
21 34 2 14 56 56 0 78 89 99
swapped 56 with 0
21 34 2 14 56 0 56 78 89 99
swapped 34 with 2
21 2 34 14 56 0 56 78 89 99
swapped 34 with 14
21 2 14 34 56 0 56 78 89 99
swapped 56 with 0
21 2 14 34 0 56 56 78 89 99
swapped 21 with 2
2 21 14 34 0 56 56 78 89 99
swapped 21 with 14
2 14 21 34 0 56 56 78 89 99
swapped 34 with 0
2 14 21 0 34 56 56 78 89 99
swapped 21 with 0
2 14 0 21 34 56 56 78 89 99
swapped 14 with 0
2 0 14 21 34 56 56 78 89 99
swapped 2 with 0
0 2 14 21 34 56 56 78 89 99

Final List: 0 2 14 21 34 56 56 78 89 99
Number of comparions 90

Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.

任何想法如何做到這一點。 我從不學習如何交換陣列

謝謝

編寫一個名為swap的函數,該函數具有void swap (int&, int&);的原型void swap (int&, int&); 交換兩個不按遞增順序排列的鄰居。

偽代碼:

void swap(int& a, int& b)
{
    if b is smaller than a
    {
        store a in some new variable c
        store b in a
        store c in b
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM