Saturday, July 23, 2016

Funky Sort

Problem: FunkySort
arr[] is an array filled with random unique integers. Arrange arr[] such that the following condition is met:
arr[0] < arr[1] > arr[2] < arr[3] > arr[4] < arr[5] ... // 23, 31, 40 , 1 // 23 < 40 > 1 < 31

import java.util.Arrays; 

public class FunkySort{
    
    public static void swap(int[] arr, int pos1, int pos2){
        int temp = arr[pos1];
        arr[pos1] = arr[pos2];
        arr[pos2] = temp;
    }
    
    public static int[] funkySort(int[] arr){
        int arrlen = arr.length;
        if(arrlen == 0 || arrlen == 1) return arr;
        int sign = 1;
        
        for(int i=0; i < arrlen-1; i++){
            if(sign == 1){
                if(arr[i] > arr[i+1]) swap(arr, i, i+1);
            } else if( sign == -1){
                if(arr[i] < arr[i+1]) swap(arr, i, i+1);
            }
            sign *= -1;
        }
        System.out.println("Array - " + Arrays.toString(arr));
        return arr;
    }
    
    public static void main(String[] args){
        int[] arr = new int[] {1,2,3,4,5};
        // funkySort(arr); 
        
        // arr = new int[]{};
        // funkySort(arr);
        
        // arr = new int[]{1};
        // System.out.println(Arrays.toString(funkySort(arr))); 
        
        //arr = new int[]{1,2,3,4,5};
        funkySort(arr); 
    }
};

No comments:

Post a Comment