Archive | October, 2010

Java : Finding top-K elements in unsorted array in linear time

17 Oct

Complexity : O(N)

public class Selection {
private static final int TOP_K = 3;
public static void main(String args[]) {
int[] _array = new int[]{9,7,8,2,1,3,5,6,4};
if (_array.length == 0) {
System.out.println("Empty Array");
System.exit(0);
} else if (_array.length == 1) {
System.out.println("Only one element, Array already sorted");
} else {
select(_array, 0, _array.length-1, _array.length-TOP_K);
}
for (int i = _array.length-TOP_K; i <= _array.length - 1; i++) {
System.out.println(_array[i]);
}
}
public static int partition(int[] input, int p, int q) {
int x = input[p];
int i = p;
for (int j = (p + 1); j <= q; j++) {
if (input[j] <= x) {
i = i + 1;
if(i < j){
int temp = input[j];
input[j] = input[i];
input[i] = temp;
}
}
}
int temp1 = input[p];
input[p] = input[i];
input[i] = temp1;
return i;
public static void select(int[] list, int left, int right, int k){
int pivotIndex = partition(list, left, right);
if(pivotIndex == k){
return;
}
else if(k < pivotIndex){
select(list, left, pivotIndex -1, k);
}else{
select(list, pivotIndex +1 , right, k);
}
}
}

Output:
run:789
BUILD SUCCESSFUL (total time: 0 seconds)

Python : finding substring in a string

6 Oct

#!/usr/bin/python

import sys

def is_substring(actual_str, pattern_str):

    if actual_str is None or pattern_str is None:
        print "empty string .. quitting"
	return

    if len(pattern_str) > len(actual_str):
        print "substring pattern is longer than actual string"
	return

    indexes = []
    for i in range(len(actual_str) - len(pattern_str) + 1):
 	if pattern_str[0] == actual_str[i] and\
	    pattern_str[len(pattern_str)-1] == actual_str[i + len(pattern_str)-1]:
	    indexes.append(i)

    if len(indexes) == 0:
        print "Substring couldn't be found!"
	return

    mismatch = False
    for j in range(len(indexes)):
        index = indexes[j]
        for k in range(len(pattern_str)):
	    if(actual_str[index] != pattern_str[k]):
	        #print "Mismatch : %s - %s"%(actual_str[index], pattern_str[k])
		mismatch = True
		break
 	    index += 1

	if mismatch == True:
	    mismatch = False
	    continue
        print "substring found at indexes : ", indexes[j]

if __name__== "__main__":
    if len(sys.argv) != 3:
        is_substring('Hello world!', 'odl')
    else:
	is_substring(str(sys.argv[1]), str(sys.argv[2]))</div>

Output :

[harit@harit-laptop scripts]$ python substr.py ’123123113456456345123′ ’456′
substring found at indexes :  9
substring found at indexes :  12

[harit@harit-laptop scripts]$ python substr.py ‘Hello world!’ ‘orl’

substring found at indexes : 7

[harit@harit-laptop scripts]$ python substr.py 12 12

substring found at indexes : 0

[harit@harit-laptop scripts]$ python substr.py 12 123

substring pattern is longer than actual string

Follow

Get every new post delivered to your Inbox.