Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Web Hosting

Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web iThemes WordPress Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


getResponse autofunnels

Liquid Web Cloud VPS Hosting

11,144 questions

15,208 answers

573 users

How to sort an array of 0, 1 and 2 values with while loop and switch in C

1 Answer

0 votes
#include <stdio.h>
  
void swap(int *a, int *b) {
    int tmp;
      
    tmp = *b;
    *b = *a;
    *a = tmp;
}
   
void sort(int *arr, int len) {
    int start = 0, mid = 0, end = len - 1;   
      
    while (mid <= end) {
        switch (arr[mid]) {
            case 0:    
                swap(&arr[start], &arr[mid]);  
                start++;      
                mid++;     
                break;
            case 1:    
                mid++;    
                break;
            case 2:     
                swap(&arr[mid], &arr[end]);  
                end--;    
                break;
        }
    }
}
  
int main() {
    int arr[] = {2, 1, 0, 0, 1, 2, 2, 1, 1, 2};
    int len = sizeof(arr)/sizeof(arr[0]); 
  
    sort(arr, len);   
  
    for (int i = 0; i < len; i++)   
        printf("%i ",arr[i]);
  
    return 0;
}
  
  
/*
run:
  
0 0 1 1 1 1 2 2 2 2 
  
*/

 




answered Apr 7 by avibootz
edited Apr 30 by avibootz
...