понедельник, 14 сентября 2015 г.

Finding palindrome in array in Java

static ArrayList<String> arr = new ArrayList<>();
public static void palidrome() throws IOException {
InputStream fis = new FileInputStream("C://tmp/palidrome.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) arr.add(line);
for (int i=0; i<arr.size(); i++) {
if (!isPal(arr.get(i))) arr.set(i, "-1");
System.out.println(arr.get(i));
}
}
public static boolean isPal(String str) {
int i=0; int k = str.length()-1;
while (i<=k) {
if (str.charAt(i)==str.charAt(k) ) {
i++;
k--;
}
else return false;
}
return true;
}

воскресенье, 6 сентября 2015 г.

Quicksort in Java example

quicksort is the fastest sorting algorithm, and here is example of method in Java:
static public void quickSort(int[] arr, int l, int r) {
        int left = l; int right = r; int tmp;
        int middle = arr[(left + right) / 2];
       
        while (left <= right) {
            while (arr[left]<middle) left++;
            while (arr[right]>middle) right--;
            if (arr[left]>arr[right]) {
                tmp = arr[left];
                arr[left] = arr[right];
                arr[right] = tmp;
            }
        }
        if (left<r) quickSort(arr, left, r);
        if (l<right) quickSort(arr, l, right);
       
    }
It needs to be called like this:
public static void main(String args[]) {
int[] array = { 4, 23,65, 76, 99, 12, 90, 34 }
quickSort(array, 0, array.length-1)
}