Problem Definition:
Problem: Given an array of integers find all pairs of integers, a and b, where a – b is equal to a given number.
For example, consider the following array and suppose we want to find all pairs of integers a and b where a – b = 3
A = [10, 4, 6, 16, 1, 6, 12, 13]
Then your method should return the following pairs:
4, 1
15, 12
13, 10
A poor solution:
There are several solutions to this problem. The most
straightforward (but inefficient) solution is to set up a nested
loop structure that goes over the elements of the array one by one
and for each element performs a sequential search on the entire
array. The running time for this algorithm is quadratic due to the
nested loop structure and the sequential search for each array
element.
Writing the straightforward inefficient solution will result in a 0. Utilize sorting (merge, quick, or radix sort) and searching to write an efficient algorithm. Becareful with which searching algorithm you choose. There is a way to write a linear search that will not devolve to the O(n2) efficiency, but one needs to be clever in how they approach this method. You may also utilize binary search which doesn’t require one to be clever.
What you need to do for this assignment
When the size of the array is very large then the quadratic
algorithm may be too slow to be useful. There are a number of
strategies that can be employed to reduce the running time, and at
this point we have covered enough topics to design a more efficient
algorithm. Based on the material covered thus far in this course,
design and implement a more efficient algorithm for this
problem.
Your algorithm must on average have a running time of O(nlogn) where n is the number of elements in the array.
The framework for your algorithm should satisfy the following criteria:
public Pair[] findPairs(int array[], int diff)
Additional Information
What you need to turn in
Briefly describe your algorithm and determine the time efficiency of it. Don’t just say, for example, that my algorithm is O(nlogn), but explain how you got that time efficiency. Remember, don’t evaluate your code. That takes too long and will give you a headache. Instead, try to conceptualize how you are solving the problem and determine the Big-O that way. Pen and paper will help with this.
package assignment.diffpairs;
import assignment.utility.ArrayUtils;
public class DifferencePairs {
// Implement your sorting algorithm here. Must be
either
// * merge sort
// * quick sort
// * radix sort
private static void sort(int arr[]) {
}
public static Pair[] findPairs(int array[], int
diff) {
return null;
}
}
public class Pair {
private int first;
private int second;
public Pair(int first, int last)
{
this.first = first;
this.second= last;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
public String toString()
{
return "(" + this.first + " , " +
this.second+ ")";
}
public boolean equals(Object other) {
if(other == null) {
return
false;
}
if(!(other instanceof Pair))
{
return
false;
}
Pair otherPair = (Pair)other;
return this.first ==
otherPair.first && this.second == otherPair.second;
}
}
package assignment.utility;
import java.util.Arrays;
public class ArrayUtils {
public static void printIntegerArray(int arr[])
{
if (arr == null) {
System.out.println("null");
return;
}
System.out.print("[ ");
for (int i = 0; i < arr.length;
i++) {
System.out.print(arr[i]);
if (i <
arr.length - 1) {
System.out.print(", ");
}
}
System.out.println(" ]");
}
public static void printObjectArray(Object arr[])
{
if (arr == null) {
System.out.println("null");
return;
}
System.out.print("[ ");
for (int i = 0; i < arr.length;
i++) {
Object obj =
arr[i];
System.out.print(obj.getClass().getName() + obj);
if (i <
arr.length - 1) {
System.out.print(", ");
}
}
System.out.println(" ]");
}
/**
* This method takes a T array and the number of
elements to truncate up to.
* The result is a new T array with elements up to, but
not including, count.
* An example:
*
* <pre>
* arr[] =
[1,2,3,4,5,6]
* truncateArray(arr,
3);
* result:
[1,2,3]
* </pre>
*
* @param arr The array to truncate.
* @param count The number of elements to keep.
* @return A T array that is the truncated version of
arr.
*/
public static <T> T[] truncateArray(T arr[], int
count) {
if (arr == null) {
throw new
IllegalArgumentException("Truncate Array: The integer array must
not be null");
}
if (count > arr.length || count
< 0) {
throw new
IllegalArgumentException("Count must be between 0 and the array
length (inclusive).");
}
return Arrays.copyOf(arr,
count);
Hello,
It seems to be a very interesting problem but doesn't get deep into existing code as it might create confusion and later at some stage you might get stuck with it.
PART 1: ANALYSIS OF PROBLEM
Since you are provided an array of n integers and all you need to find is the pairs(a,b) such that a-b=Given Value.
So, this is a great example of an optimization problem.
PART 2: THINK ABOUT NAIVE SOLUTION FIRST
If a problem is given, don't just jump to solve it optimally for the very first time. Read the problem statement multiple times, it might give you some hint about how to solve the problem or where you had earlier saw similar problems.
So, once you understood the problem statement, try to find the naive solution.
PART 3: NAIVE SOLUTION
If you think about this particular problem, you can think of:
The simplest method will be running two loops, the outer loop picks the first element (bigger element) and the inner loop looks for the smaller. The time complexity of this method is O(n^2).
PART 4: NEW APPROACH TO OPTIMIZE THE SOLUTION
You can think about sorting in O(N*LogN) and then we can search in O(N) to find all the pairs.
Sorting Techniques could be Merge Sort, Heap Sort, etc.
Radix, Counting sort will fail when the input size will increase. So, they will be not advisable for larger inputs.
PART 5: ALGORITHM
Please find the algorithm below and try to incorporate with your code:
* Sort the array using Merge, Heapsort in O(n*Log n) Time complexity
* Now take two indices as i=0 and j=1 for iteration purpose.
* Now check when (i!=j and arr[j] - arr[i] == GivenNumber)
* Print Pair as arr[j], arr[i]
* If arr[j] - arr[i] < GivenNumber, increment j (because the difference is smaller, so bigger number is required)
* else increment i
* Repeat till the end of array is reached.
PART 6: CODING IMPLEMENTATION
static void findPair(int arr[],int n)
{
// Sort using Arrays Class, Java.util.arrays class must be imported
Arrays.sort(arr);
int size = arr.length;
// Take two indices
int i = 0, j = 1;
// Iterate till the end of Array
while (i < size && j < size) // Boundary
Checking
{
if (i != j && arr[j]-arr[i] == n)
{
System.out.print(arr[j] + " " + arr[i]);
}
else if (arr[j] - arr[i] < n)
j++;
else
i++;
}
System.out.print("No such pair");
}
This is the compiled solution and i will recommend you to practice more and incorporate these changes in your project.
Remember, real learning is achieved by these milestones only.
All the best and please provide a feedback if it really helped you.
********************COMPLETE***************************
Problem Definition: Problem: Given an array of integers find all pairs of integers, a and b,...
Our 1st new array operation/method is remove. Implement as follows: public static boolean remove( int[] arr, int count, int key ) { 1: find the index of the first occurance of key. By first occurance we mean lowest index that contains this value. hint: copy the indexOf() method from Lab#3 into the bottom of this project file and call it from inside this remove method. The you will have the index of the value to remove from the array 2:...
(JAVA) Given an array of unique positive integers, write a function findSums that takes the array input and: 1. Creates a hashtable called “hashT” and inserts all the elements of the input array in the hashtable. 2. Finds pairs of elements in the hashtable whose sum is another element (sum) in the hashtable and print the pairs in the console. 3. Returns another hashtable names “sums” of those sum elements. For example: Input: [1,5,4,6,7,9] Output: [6,5,7,9] Explanation: 6 = 1...
must provide the following public interface: public static void insertSort(int [] arr); public static void selectSort(int [] arr); public static void quickSort(int [] arr); public static void mergeSort(int [] arr); The quick sort and merge sort must be implemented by using recursive thinking. So the students may provide the following private static methods: //merge method //merge two sorted portions of given array arr, namely, from start to middle //and from middle + 1 to end into one sorted portion, namely,...
Java: Write an application that has an array of at least 20 integers. It should call a method that uses the sequential search algorithm to locate one of the values. The method should keep a count of the number of comparisons it makes until it finds the value. Then the program should call another method that uses the binary search algorithm to locate the same value. It should also keep count of the number of comparisons it makes. Display these...
Given a bubble sort and the following array: [10,7,19,5,16] What are the values after the first iteration? Given an insertion sort and the following array: [50,5,35,70,6] What does the array look like after the first insertion: Fill in the missing code for InsertionSort method // Insertion Sort method //sorts an array of Auto objects public static void insertionSort(Auto [] arr) { Auto temp; int j; for (int i=1; i<arr.length; i++) { j=i; temp=arr[i]; while (j!=0 &&(temp.getModel().compareTo(arr[[j-1].getModel())<0)...
I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....
Implement the bubble sort algorithm described here: While the array is not sorted For each adjacent pair of elements If the pair is not sorted Swap the elements Use the BubbleSorter class to fill in the code and make it run with the BubbleSorterDemo class. BubbleSorter.java public class BubbleSorter { /** Sort an integer array using the bubble sort algorithm. @param arr array of integers to sort */ public static void sort(int[] arr) { // Your...
I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...
Submissions) Part A Type and run the Array class template discussed in lecture (Templates notes). Modify the class by adding sort member function (refer to Algorithm Analysis notes for sorting algorithms) Sample usage: a. sort(); Add the needed code in main to test your function. template <class T> 1/you can use keyword typename instead of class class Array { private: T *ptr; int size; public: Array(T arr[], int s); void print(); template <class T> Array<T>:: Array (T arr[], int s)...
the code needs to be modifed. require a output for the
code
Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...