Question:

BubbleSort in C# doesn't seem to work

by  |  earlier

0 LIKES UnLike

int[] array = { 2, 7, 6, 5, 9, 8, 7, 6, 9 };

bool swapped = false ;

while (swapped)

{

swapped = true;

int position = 0;

while (position < array.Length)

{

if (array[position] >= array[position 1])

{

int Temp = array[position 1];

array[position 1] = array[position];

array[position] = Temp;

}

position ;

}

for(int i = 0;i<9;i )

{

Console.Write(array[i] ",");

}

}

 Tags:

   Report

2 ANSWERS


  1. swapped is false, so the while loop is never entered.


  2. Previous responder correct about the entire while being skipped. Also, this is not a valid bubble sort, as it will only bubble the largest value to position 1. To sort the entire array, you have to have loop thru successively smaller sections of your array:

    for i 0-&gt;8

    for j (i+1)-&gt;9

    if (array[i] ? array[j]) (?=&#039;&lt;&#039; if sorted descending, &#039;&gt;&#039; if ascending)

    swap items

Question Stats

Latest activity: earlier.
This question has 2 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.
Unanswered Questions