Advertisement
Ronnie72428

Pendulum Array

Nov 30th, 2021
1,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Q_9{
  4.    
  5.     public static void main( String args[] ){
  6.         System.out.print('\u000C');
  7.        
  8.         Scanner sc = new Scanner( System.in );
  9.        
  10.         System.out.println("Enter the size of the array:");
  11.         int size = sc.nextInt();
  12.        
  13.         if( size <= 0 ){
  14.             System.out.println("Invalid size. Value must more than 0");
  15.             System.exit(0);
  16.         }
  17.        
  18.         int data[] = new int[size];
  19.        
  20.         System.out.println("Enter the values for the array:");
  21.         for( int i = 0; i < size; i++ )
  22.             data[i] = sc.nextInt();
  23.        
  24.         Arrays.sort( data );
  25.        
  26.         System.out.println("OUTPUT:");
  27.        
  28.         int pendulum_arr[] = new int[size];
  29.         pendulum_arr = PendulumSort(data);
  30.        
  31.         for( int i = 0; i < size; i++ )
  32.             System.out.print(pendulum_arr[i] +" ");
  33.        
  34.         System.exit(0);
  35.     }
  36.    
  37.    
  38.     public static int FetchSmallest(int[] data, int startIndex, int endIndex){
  39.         int
  40.             smallest = data[startIndex];
  41.            
  42.         if( endIndex >= data.length )
  43.             endIndex = data.length - 1;
  44.            
  45.         for( int i = startIndex; i <= endIndex; i++ ){
  46.             if( smallest > data[i] )
  47.                 smallest = data[i];
  48.         }
  49.        
  50.         return smallest;
  51.     }
  52.    
  53.     public static int[] PendulumSort(int data[]){
  54.        
  55.         int
  56.             size = data.length,
  57.             iteration = 0,
  58.             index = ( size / 2 ),
  59.             sorted[] = new int [ size ];
  60.            
  61.         for(int i = 0; i < size; i++)
  62.             sorted[i] = data[i];
  63.            
  64.         boolean setLeft = true;
  65.        
  66.         while( iteration < size ){
  67.            
  68.             sorted[index] = FetchSmallest(data, iteration++, size);
  69.            
  70.             if( setLeft)
  71.                 index = index - iteration;
  72.             else
  73.                 index = index + iteration;
  74.            
  75.             if( index < 0 || index >= size )
  76.                 break;
  77.            
  78.             setLeft = !setLeft;
  79.         }
  80.        
  81.         return sorted;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement