Пытаясь понять, что не так с моим методом сортировки пузырьков

Я не уверен, почему мой код не работает. Все они печатают одинаковые значения, а не сортируют их.
Выходные данные не меняются, и массивы, кажется, еще не отсортированы. Есть идеи, как я могу это исправить? Я хотел бы узнать, почему.

    void BSort::BubbleSort()
{   int temp =0;
for(int index = 0; index < sizes; index++){
for(int index2 = 0; index2 < sizes-1; index2++ ){
if(Array1[index2] > Array1[index2+1]){
temp = Array1[index2];
Array1[index2] = Array1[index2+1];
Array1[index2+1] = temp;           }
}
}}

/*************************************************************************/
//---------------------------  BubbleSort2( )  --------------------------//
/*************************************************************************/void BSort::BubbleSort2()
{
int temp =0;
for(int index = 0; index < sizes-1; index++){
for(int index2 = sizes-1; index2 > index; index2--){
if( Array2[index2] < Array2[index2-1]){
temp = Array2[index2];
Array2[index2] = Array2[index2-1];
Array2[index2-1] = temp;
}
}
}
}

/*************************************************************************/
//-----------------------------  CombSort( )  ---------------------------//
/*************************************************************************/void BSort::CombSort() {
int temp = 0;
int tempsize =sizes;
int index2;
while((tempsize = int(tempsize/1.3)) >1){
for(int index = sizes-1; index >= tempsize; index--){
index2 = index-tempsize;
if(Array3[index] < Array3[index2]){
temp = Array3[index];
Array3[index] = Array3[index2];
Array3[index2] = temp;
}
}
bool testcase = true;
for(int in = 0; in < sizes; in++){
for(int in2 =sizes-1,testcase = false; in2 > in; in2--){
if(Array3[in2] < Array3[in2-1])
{ temp = Array3[in2];
Array3[in2] = Array3[in2-1];
Array3[in2-1] = temp;
testcase = true;
}
}
}
}}

Основной файл

#include<iostream>#include<cstdlib>

#include "BSort.h"using namespace std;int main(void)
{int a[] = {-2, 88, 6, -1, 10, 15, 3, 12, -11, 9, 33, 21, 4, 7, 45, 55, 62, 18, 0, 20};BSort S(a,20);cout << endl << " Display Array elements before sorting";
S.DisplayListElements();

// Calling bubble sort
S.BubbleSort();
S.BubbleSort2();
S.CombSort();

cout << endl << endl << " Display Array elements Increasing order After BubbleSort";
S.DisplayListElements();system("pause");
return 0;
}

1

Решение

Попробуйте это .. В основном после каждой итерации вам нужно запускать внутренний цикл на одну единицу меньше, чем внешняя переменная … в основном потому, что она уже отсортирована

 void BSort::BubbleSort()
{   int temp =0;
for(int index = 0; index < sizes; index++){
for(int index2 = 0; index2 < sizes-index; index2++ ){
if(Array1[index2] > Array1[index2+1]){
temp = Array1[index2];
Array1[index2] = Array1[index2+1];
Array1[index2+1] = temp;           }
}
}}
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector