Tuesday, June 7, 2016

Manual Right Cyclic Array Rotation Ala Hyosoka di Java

Method yang ini bisa dipake buat right cyclic array rotation,... Daan methodnya udah lulus uji dari codility... Berikut Kodenya :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/*
  * A = array yang akan dirotasi
  * k = besar rotasi ke kanan
  */
 
 public static int[] cyclicRotation(int[] A, int k)
 {
  if(A.length<=1) return A;
  int[] temp = new int[A.length];
  int rot = (k/A.length) > 0 ? k%A.length: k;
  for(int i=0; i<A.length; i++)
  {
   if(A.length - i > rot) temp[rot+i] = A[i];
   else temp[rot-(A.length-i)] = A[i];
  }
  return temp;
 }

Hasil Uji dari Codiliti :


Sorting & Binarysearch Array di Java

mmmm...... to the point :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package hisoka.poipo;

import java.util.Arrays;

public class MainArraySorting {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int[] hisoka = {-1,8, 4,7,2,10,3,2};
  displayArray(hisoka);
  Arrays.sort(hisoka);
  System.out.println("\nSetelah di sort : ");
  displayArray(hisoka);
  
  //ini pake binarySearch
  int indeks = Arrays.binarySearch(hisoka, 7);
  System.out.println(indeks);
 }
 
 
 public static void displayArray(int[] A)
 {
  for (int a: A)
  {
   System.out.print(a+" ");
  }
  System.out.print("\n");
 }

}

Hasil :
Sooo..untuk ngesort array itu pake cara di line 11, terus klu binarySearch di line 16 ehehe.. :D