![](/img/trans.png)
[英]unable to predict the output when we use do-while loop and write constants in while loop seperated by comma
[英]Unable to use do-while loop correctly to implement a bubble sort
//create swap function
void swap(int* a, int* b)
{
//implement swap function
int temp = *a;
*a = *b;
*b = temp;
}
void sort(int arrayofval[], int n)
{
int burst = 0;
do
{
for(int i=0, burst = 0; i < n; i++)
if(arrayofval[i] > arrayofval[i+1])
{
swap(&arrayofval[i], &arrayofval[i+1]);
burst++;
}
}
while(burst != 0);
return;
你好! 我正在嘗試在C中實現冒泡排序和交換功能,並且碰壁了:-(調試時,似乎交換功能和初始循環有效。但是,似乎我的函數在第一個之后退出循環並且不重復循環>交換值過程,因為以下條件:
while(突發!= 0)
沒有運行。 誰能幫助我進一步了解這一點?
它工作得很好,除了您應該i < n-1
,因為arrayofval[i+1]
對於i = n-1
會指向數組之外。
#include <stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void sort(int arrayofval[], int n)
{
int burst, i = 0;
do
{
for(i=0, burst = 0; i < n-1; i++)
if(arrayofval[i] > arrayofval[i+1])
{
swap(&arrayofval[i], &arrayofval[i+1]);
burst++;
}
}
while(burst != 0);
}
int main( int argc, char ** argv ) {
int list[] = {3,2,1};
sort( list, 3 );
printf("%d %d %d\n", list[0], list[1], list[2] );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.