- Implements a function that, given an array, requires that the negative numbers in the array precede all positive numbers
Implementing a function, given an array, requires that the negative number in the array be in the first positive number in the last 0 in the middle
1#include <stdio.h>2#include <stdlib.h>3 4 //Output array elements5 voidPrintint*arr,intlen);6 //Exchange two numbers7 voidSwapint*left,int*Right );8 //put all positive numbers in the back row9 voidSort_two (int*arr,intlen);Ten //Put negative numbers in front, 0 in the middle, integers in the back One voidSort_three (int*arr,intlen); A - intMain () - { the intarr[ One] = {1,0,-2,5,7,8,-1,-5,-9,-7,0}; -printf"before sorting: \ n"); -Print (arr, One); - +printf"after sorting: \ n"); - //Sort_two (arr,11); +Sort_three (arr, One); APrint (arr, One); at - return 0; - } - - //put all positive numbers in the back, essentially a two-color sort problem, like the idea of a fast line - voidSort_two (int*arr,intlen) in { - intleft =0, right = Len-1; to while(Left <Right ) + { - //jump out of a loop when a positive number is found from left to right the while(Arr[left] <=0) *left++; $ //jumps out of the loop when a non-positive number is found from right to leftPanax Notoginseng while(Arr[right] >0) -right--; the //be sure to have + if(Left <Right ) ASwap (arr+left,arr+Right ); theleft++; +right--; - } $ } $ - //essentially a three-color sorting problem - voidSort_three (int*arr,intlen) the { - intLeft, Curr, right;//three-color working handsWuyileft =0;//record the next element at the end of a negative sequence theCurr =0;//record the next element of the 0 sequence -right = Len-1;//record the previous element in the front of a positive sequence Wu - while(Curr <=Right ) About { $ if(Arr[curr] = =0)//0 -curr++; - Else if(Arr[curr] <0)//Negative number - { ASwap (arr+curr,arr+Left ); +curr++; theleft++; - } $ Else//Positive the { theSwap (arr+curr,arr+Right ); theright--; the } - } in } the the voidSwapint*left,int*Right ) About { the*left ^= *Right ; the*right ^= *Left ; the*left ^= *Right ; + } - the voidPrintint*arr,intlen)Bayi { the inti; the for(i =0; i < Len; i++) -printf"%4d", * (arr+i)); -printf"\ n"); the}
Operation Result:
Two-color, three-color sorting problems