面试问题:C程序排序为O二进制数组(N)二进制数、程序、问题

由网友(愛上了。。)分享简介:我想出下面的程序做到这一点,但它似乎没有工作,进入无限循环。它的工作类似于快速排序。INT主要(){INT ARR [] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1};INT 18例;INT *前,*最后;前面= ARR;最后= ARR + N;而(前< =上){而((前&LT...

我想出下面的程序做到这一点,但它似乎没有工作,进入无限循环。它的工作类似于快速排序。

  INT主要()
{
 INT ARR [] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1};
 INT 18例;
 INT *前,*最后;

 前面= ARR;
 最后= ARR + N;
 而(前< =上)
 {
  而((前<最后)及及(*前== ​​0))
   前++;

  而((前<最后)及及(*最后== 1))
   持续 - ;

  如果(前<上)
  {
   INT TEMP = *前;
   *前= *最后,
   *最后=温度;
   前++;
   持续 - ;
  }
 }
 的for(int i = 0; I&n种;我++)
  的printf(%D,编曲[I]);

 返回0;
}
 

解决方案

我看到节目至少有两个问题:

第1题:

 末页= ARR + N;
 

不正确。它应该是:

 末页= ARR + N  -  1;
 
十进制转化二进制,c语言用调用函数

由于

 (ARR + 0)指向第0 ELE
(ARR + 1)指向第一ELE
...
(改编+ N-1)点到(N-1)个ele..which是最后一个元素。
 

Problem2: 接下来while循环:

 而(前< =上)
 

是不正确的,应该是:

 而(前<上)
 

在你的情况时,前一个和最后成为平等的,你的循环继续,但 既不正面也不是最后一个获得在这一点修改,造成死循环。

在前面,最后成为平等的,这是没有问题,继续,你的阵 本来排序即可。

I've come up with the following program to do it, but it does not seem to work and goes into infinite loop. Its working is similar to quicksort.

int main()
{
 int arr[] = {1,1,0,1,0,0,0,1,0,1,0,1,0,1,0,1,0,1};
 int N = 18;
 int *front, *last;

 front = arr;
 last = arr + N;
 while(front <= last)
 {
  while( (front < last) && (*front == 0) )
   front++;

  while( (front < last) && (*last == 1) )
   last--;

  if( front < last)
  {
   int temp = *front;
   *front = *last;
   *last = temp;
   front ++;
   last--;
  }
 }
 for(int i=0;i<N;i++)
  printf("%d ",arr[i]);

 return 0;
}

解决方案

I see at least two problems in the program:

Problem 1:

last = arr + N;

is incorrect. It should be:

last = arr + N - 1;

because

(arr + 0) points to 0th ele
(arr + 1) points to 1st ele
...
(arr + N -1) points to (N-1)th ele..which is the last element.

Problem2: Next your while loop:

while(front <= last)

is incorrect and should be:

while(front < last)

In your case when front and last become equal, your loop continues but neither front nor last get modified at this point, resulting in infinite loop.

When front and last become equal, it makes no point to continue, your array would have been sorted by then.

阅读全文

相关推荐

最新文章