Jump search with Strings - java

i have been doing research on the jump search algorithm in an array. But i am confused on how you can use the search method with strings. Can anyone give me a link on where to look, or an example on here? Every example i have seen has been with numbers
public class JumpSearch
{
public static int jumpSearch(int[] arr, int x)
{
int n = arr.length;
int step = (int)Math.floor(Math.sqrt(n));
int prev = 0;
while (arr[Math.min(step, n)-1] < x)
{
prev = step;
step += (int)Math.floor(Math.sqrt(n));
if (prev >= n)
return -1;
}
while (arr[prev] < x)
{
prev++;
if (prev == Math.min(step, n))
return -1;
}
if (arr[prev] == x)
return prev;
return -1;
}
public static void main(String [ ] args)
{
int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21,
34, 55, 89, 144, 233, 377, 610};
int x = 55;
// Find the index of 'x' using Jump Search
int index = jumpSearch(arr, x);
System.out.println("\nNumber " + x +
" is at index " + index);
}
}

Related

Search an element in sorted 2d matrix

package kunal;
import java.util.Arrays;
public class SortedMatrix {
public static void main(String[] args) {
int[][] matrix = {
{20, 30, 40, 45},
{50, 55, 60, 65, 66, 67},
{70, 71, 72, 73},
{74, 75, 78, 80}
};
int target = 67;
System.out.println(Arrays.toString(search(matrix, target)));
}
static int[] search(int[][] matrix, int target) {
// return the index of floor number
int floorIndex = floor(matrix, target);
int binarySearch = binarySearch(matrix, target, floorIndex);
if(binarySearch != -1) {
return new int[] {floorIndex, binarySearch};
}
return new int[] {-1, -1};
}
static int floor(int[][] matrix, int target) {
int start = 0;
int end = matrix.length - 1;
int colFix = 0;
while(start <= end) {
int mid = start + (end - start)/2;
if(target == matrix[mid][colFix]) {
return mid;
}
if(target > matrix[mid][colFix]) {
start = mid + 1;
}else {
end = mid - 1;
}
}
return end;
}
static int binarySearch(int[][] matrix, int target, int floorIndex) {
int start = 0;
int end = matrix[floorIndex].length - 1;
int rowFix = floorIndex;
while(start <= end) {
int mid = start + (end - start)/2;
if(target == matrix[rowFix][mid]) {
return mid;
}
if(target > matrix[rowFix][mid]) {
start = mid + 1;
}else {
end = mid - 1;
}
}
return -1;
}
}
In this code first I find the floor(largest number smaller than or equal to the traget) in the first column. after that applying the binary search in the row where i found floor.
this code works on eclispe editor. And successfully run on leetcode too but when i try to submit it shows runtime error. "index -1 out of bond for length 1". please correct the code

Java: Binary Search

Is this an ok implementation of the binary search algorithm? It works but its an implementation I came up with and differs from my instructors. Can anyone punch a hole in it for me?
package algorithm.linearsearch;
public class BinarySearch {
public static void main(String[] args) {
System.out.println(binarySearch(
new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 26, 109, 1001, 1100 },
26));
}
private static int binarySearch(int[] array, int target) {
int p = 0;
int r = array.length - 1;
int q;
while (p <= r) {
q = (p + r) / 2;
if (array[q] == target) {
System.out.println("value: " + array[q]);
return q;
}
if (array[q] > target) {
r = q + 1;
} else {
p = q - 1;
}
}
return -1;
}
}
Just this
if (array[q] > target) {
r = q + 1;
} else {
p = q - 1;
}
should be
if (array[q] > target) {
r = q - 1; // index lower to current pivot
} else {
p = q + 1; // index upper to current pivot
}
One thing i can say. Your program is expected to return index if found or return -1 if not found. So you don't need to print value as its input taken from user regarding which element to find.
You need a check initially if your array is null return -1 to avoid null pointer exception which will happen when you calculate length of array.

Quick Sort not sorting iterative solution

I currently have the below code for my quick sort. As you can see it is not producing the correct output. Any help will be greatly appreciated. I need the pivot to be the first item in the array. As you can also see i am measuring the time it takes to run, but please ignore that for the time being.
edit: to be specific it works correctly when i have a list in descending order and ascending order(already sorted), but when i try a random list it does not work.
Output:
QuickSort:
Quick Sort Took 181023 nanoseconds
Quick Sort Took 0 milliseconds
Sorted Quick Sort: 25, 12, 17, 13, 20, 7, 5, 16, 11, 26, 24, 18, 9, 4, 21, 1, 23, 27, 15, 19, 28, 14, 8, 22, 6, 3, 2, 10, 29, 40, 37, 32, 44, 38, 35, 41, 39, 31, 42, 30, 43, 36, 34, 33, 45, 46, 47, 48, 49, 50,
Code:
class QuickSort {
public static int Partition(int[] numbers, int left, int right){
//selects the first item at position [0] as the pivot
//left is given 0 when the method is called
int pivot = numbers[left];
while (true)
{
while (numbers[left] < pivot)
left++;
while (numbers[right] > pivot)
right--;
if (left < right)
{
int temp = numbers[right];
numbers[right] = numbers[left];
numbers[left] = temp;
}
else
{
return right;
}
}
}
//method to check for special cases
public static void QuickSort_Check(int[] numbers, int left, int right)
{
//special case of 2 items to be sorted
if(right == 1){
if(numbers[0] >= numbers[1]){
System.out.print("This is a special case of 2 inputs: ");
System.out.print(numbers[1] + ", " + numbers[0]);
System.exit(0);
}
else {
System.out.print("This is a special case of 2 inputs: ");
System.out.print(numbers[0] + ", " + numbers[1]);
System.exit(0);
}
System.exit(0);
}
//special case of 1 item to be sorted
else if (right == 0){
System.out.print("This is a special case of 1 input: ");
System.out.print(numbers[0]);
System.exit(0);
}
else {
QuickSort_Iterative(numbers, left, right);
}
}
public static class QuickPosInfo
{
public int left;
public int right;
};
public static QuickPosInfo spot = new QuickPosInfo();
public static void QuickSort_Iterative(int[] numbers, int left, int right)
{
if(left >= right)
return; // Invalid index range
LinkedList<QuickPosInfo> list = new LinkedList< QuickPosInfo>();
spot.left = left;
spot.right = right;
list.add(spot);
while(true)
{
if(list.size() == 0)
break;
left = list.get(0).left;
right = list.get(0).right;
list.remove(0);
int pivot = Partition(numbers, left, right);
if(pivot > 1)
{
spot.left = left;
spot.right = pivot - 1;
list.add(spot);
}
if(pivot + 1 < right)
{
spot.left = pivot + 1;
spot.right = right;
list.add(spot);
}
}
}
}
This partition method correctly sorted half the array, then did not sort the other half so I believe the problem is in your QuickSort_Iterative(); when the pivot equals 21 it just infinitely swaps 20 and 21.
private static int partition(int[] arr,int left,int right) {
int pivot = arr[right];
int small = left-1;
for(int k = left;k < right;k++)
{
if(arr[right] <= pivot)
{
small++;
swap(arr,right,small);
}
}
swap(arr,right,small+1);
System.out.println("Pivot= "+arr[small+1]);//prints out every sort
System.out.println(Arrays.toString(arr));
return small+1;
}
private static void swap(int[] arr, int k, int small) {//easy swap method
int temp;
temp = arr[k];
arr[k] = arr[small];
arr[small] = temp;
}
UPDATE
Here is the requested method. I believe that the problem with your original one is that you are not modifying that values of left and right properly as the array is sorted.
void QuickSort(int arr[], int left, int right)
{
// create auxiliary stack
int stack[] = new int[right-l+1];
// initialize top of stack
int top = -1;
// push initial values in the stack
stack[++top] = left;
stack[++top] = right;
// keep popping elements until stack is not empty
while (top >= 0)
{
// pop right and l
right = stack[top--];
left = stack[top--];
// set pivot element at it's proper position
int p = partition(arr, left, right);
// If there are elements on left side of pivot,
// then push left side to stack
if ( p-1 > left )
{
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
// If there are elements on right side of pivot,
// then push right side to stack
if ( p+1 < right )
{
stack[ ++top ] = p + 1;
stack[ ++top ] = right;
}
}
}
I don't know that will help you out or not you can also try the below code for same.
public class Demo {
private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
i++;
j--;
}
}
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[]){
Demo sorter = new Demo();
int[] input = {8,693,29,3,2,8,29,82,4,26,2,62,82,6,52,9,42,6,52,66,2,8};
sorter.sort(input);
for(int i:input){
System.out.print(i);
System.out.print(" ");
}
}
}

how to perform insertion sort recursively

I have two methods that I intend to perform an insertion sort on an array of ints. The first method does the outer loop of the insertion sort algorithm while the second method inserts the particular element in the correct position recursively. For example:
int [] list = {20, 50, 30, 10, 60, 40};
sort(list);
The result should be {10,20,30,40,50,60}
My problem is in the insert method; Here is my code:
public static void sort(int[] list) {
int position;
for (position = 1; position < list.length; position++) {
insert(list, list[position], position);
}
}
public static void insert(int[] list, int element, int position) {
int position2 = position - 1;
if (position == list.length - 1) {
// do nothing
} else {
while ((position > 0) && (list[position - 1] > element)) {
element = list[position - 1];
insert(list, element, position - 1);
}
list[position] = element;
}
}
Currently my output is,
{20, 50, 50, 50, 60, 40}
I do not completely understand recursion. Please help
When you make some function recursive, there should be a recursion end condition along with other conditions.
Run this version and try to see what is that you're doing wrong.
Try this version:
public static void insertInOrder(int element, int[] a, int first, int last) {
if (element >= a[last])
a[last + 1] = element;
else if (first < last) {
a[last + 1] = a[last];
insertInOrder(element, a, first, last - 1);
}
else // first == last and element < a[last]
{
a[last + 1] = a[last];
a[last] = element;
}
}
public static void insertion_sort_recur(int[] arr, int first, int last) {
if (first < last) {
insertion_sort_recur(arr, first, last - 1); // avoids looping thru arr[0..last-1]
insertInOrder(arr[last], arr, first, last - 1); // considers arr[last] as the first element in the unsorted list
}
}
public static void main(String args[]) {
int A[] = { 5, 3, 2, 4, 6, 1 };
insertion_sort_recur(A, 0, 5);
for(int i=0; i < A.length; i++) {
System.out.println(A[i]);
}
}
Source:
http://analgorithmaday.blogspot.com/2011/01/insertion-sortrecursive-method.html
Try below code by providing else as an integer array, with sortedIndex as index of first element and and index as index of second element:
public static void insertionSort(int[] ele, int sortedIndex, int index) {
if (sortedIndex < ele.length) {
if (index < ele.length) {
if (ele[sortedIndex] > ele[index]) {
ele[sortedIndex] += ele[index];
ele[index] = ele[sortedIndex] - ele[index];
ele[sortedIndex] = ele[sortedIndex] - ele[index];
}
insertionSort(ele, sortedIndex, index + 1);
return;
}
if (index == ele.length) {
sortedIndex++;
}
insertionSort(ele, sortedIndex, sortedIndex + 1);
}
}

how to print out the number of times a loop happened? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm am trying to determine how many comparisons are made for both the linear and binary searching techniques. can someone tell me how to print out the number of times a loop happened in each case? for example, to find 5 in the first array the loop happens only one time.
public static void main(String[] args) {
// TODO code application logic here
int[] values = {5, 8, 6, 2, 1, 7, 9, 3, 0, 4, 20, 50, 11, 22, 32, 120};
int[] valuesSorted = {1, 2, 3, 4, 5, 8, 16, 32, 51, 57, 59, 83, 90, 104};
DisplayArray(values);
DisplayArray(valuesSorted);
int index;
index = IndexOf(1, values);
System.out.println("1 is at values location " + index);
index = IndexOf(120, values);
System.out.println("120 is at values location " + index);
index = BinaryIndexOf(104, valuesSorted);
System.out.println("104 is at values Sorted location " + index);
index = BinaryIndexOf(90, valuesSorted);
System.out.println("90 is at values Sorted location " + index);
}
public static int IndexOf(int value, int[] array)
{
for (int i=0; i < array.length; i++)
{
if(array[i] == value)
return i;
}
return -1;
}
public static int BinaryIndexOf(int value, int [] array)
{
int start = 0;
int end = array.length -1;
int middle;
while (end >= start)
{
middle = (start + end ) /2;
if (array[middle]== value)
return middle;
if (array[middle]< value)
start = middle + 1;
else
end = middle - 1;
}
return -1;
}
public static void DisplayArray(int[] array)
{
for (int a : array)
{
System.out.print(a + " ");
}
System.out.println();
}
}
For the linear search, you can do something like this:
public static int IndexOf(int value, int[] array)
{
for (int i=0; i < array.length; i++)
{
if(array[i] == value)
{
System.out.println("Linear search: Number of comparisons = " + (i + 1));
return i;
}
}
return -1;
}
For the Binary Search, do this:
public static int BinaryIndexOf(int value, int [] array)
{
int start = 0;
int end = array.length -1;
int middle;
int loopCount = 0;
while (end >= start)
{
loopCount++;
middle = (start + end ) /2;
if (array[middle]== value)
{
System.out.println("Binary search: Number of times looped = " + loopCount);
return middle;
}
if (array[middle]< value)
start = middle + 1;
else
end = middle - 1;
}
System.out.println("Binary search: Number of times looped = " + loopCount);
return -1;
}
One easy way is to make a counter variable inside your class, and manipulate it as needed, like this:
private static int _loopCounter;
public static void main(String[] args) {
// TODO code application logic here
int[] values = {5, 8, 6, 2, 1, 7, 9, 3, 0, 4, 20, 50, 11, 22, 32, 120};
int[] valuesSorted = {1, 2, 3, 4, 5, 8, 16, 32, 51, 57, 59, 83, 90, 104};
DisplayArray(values);
DisplayArray(valuesSorted);
_loopCounter = 0;
int index;
index = IndexOf(1, values);
System.out.println("1 is at values location " + index);
System.out.println(_loopCounter + " comparisons were made.")
_loopCounter = 0;
index = IndexOf(120, values);
System.out.println("120 is at values location " + index);
System.out.println(_loopCounter + " comparisons were made.")
_loopCounter = 0;
index = BinaryIndexOf(104, valuesSorted);
System.out.println("104 is at values Sorted location " + index);
System.out.println(_loopCounter + " comparisons were made.")
_loopCounter = 0;
index = BinaryIndexOf(90, valuesSorted);
System.out.println("90 is at values Sorted location " + index);
System.out.println(_loopCounter + " comparisons were made.")
}
public static int IndexOf(int value, int[] array)
{
for (int i=0; i < array.length; i++)
{
_loopCounter++;
if(array[i] == value)
return i;
}
return -1;
}
public static int BinaryIndexOf(int value, int [] array)
{
int start = 0;
int end = array.length -1;
int middle;
while (end >= start)
{
_loopCounter++;
middle = (start + end ) /2;
if (array[middle]== value)
return middle;
if (array[middle]< value)
start = middle + 1;
else
end = middle - 1;
}
return -1;
}
public static void DisplayArray(int[] array)
{
for (int a : array)
{
System.out.print(a + " ");
}
System.out.println();
}
I didn't test this code, but I'll bet you can modify it to work how you want.

Categories

Resources