Printing unique elements repeated more than once - java

How do you print a unique array consisting of elements only repeated more than once in an original array in Java? For example, there is an array a = {1,2,2,2,3,4,5,5}, the output should be {2,5}. It should be using only arrays.
I have attempted the question and this is what I've done so far:
for (int i = 0; i < a.length; i++) {
int j;
for (j = 0; j < i; j++) {
if (a[i] == a[j]) break;
}
if (i == j) System.out.print(a[i]+" ");
}
The output is all the unique elements in the array, but I am trying to print the ones that are specifically repeated more than once.

Assuming the input array contains elements that are Comparable or otherwise primitive types, you can follow these steps. The goal is essentially to find the last element of all chains of length > 1.
Sort the array using Arrays.sort (if necessary).
Iterate over the array, starting at the second element. For each element:
If the preceding element is equal to the current element,
and the succeeding element is not equal to the current element (or if there is no succeeding element)...
Then print the current element.
Note: If you had access to a HashMap, there would be an O(n) version of this O(n log(n)) algorithm.
Here it is in code:
public static void printDuplicates(int[] a) {
Arrays.sort(a);
for (int i = 1; i < a.length; i++) {
boolean precIsEqual = (a[i-1] == a[i]);
boolean succIsEqual = (i+1 != a.length) && (a[i+1] == a[i]);
if (precIsEqual && !succIsEqual) {
System.out.print(a[i] + " ");
}
}
}
Ideone Demo
Output: 2 5

Related

Numerical sort with multiple lists of ascending values

I've had trouble articulating a simple way to break this question down in to a question title, and therefore a google search.
I'm wondering if there is a sorting algorithm already defined that can sort an array of numbers without keeping pairs adjacent. Easier to explain with an example:
Values:
1,3,5,2,1,3,2,4
A normal numerical sort would come out as:
1,1,2,2,3,3,4,5
What I would like:
1,2,3,4,5,1,2,3
I could hack this together, I just want to know if there is a name for this kind of sort.
Nothing exists, but the algorithm is simple enough:
separate dupes into tmplist
sort list
add list to result
switch list and tmplist
repeat while list is non-empty
You may use the common selection sort algorithm and make some modification to it.
For example:
static void modifiedSelectionSort(int[] arr)
{
Integer lastSelection = null;
for (int i = 0; i < arr.length - 1; i++)
{
// Find the minimum element in unsorted array which is greater than lastSelection
Integer minIdx = null;
for (int j = i; j < arr.length; j++)
if ((minIdx == null || arr[j] < arr[minIdx]) && (lastSelection == null || arr[j] > lastSelection))
minIdx = j;
// Check whether the last selection is the greatest number
if (minIdx == null) {
lastSelection = null;
i--;
} else {
// Store the last selection
lastSelection = arr[minIdx];
if (minIdx != i) {
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
}
}
I think there is no name for this special sorting method.

How to implement a k-way merge sort?

I need to implement a function which does a k-way merge sort on an unsorted array or integers.
The function takes in two parameters, an integer K, which is the "way" of the sort and always a power of 2. The second parameter is the array of integers to be sorted, whose length is also a power of 2.
The function is to return an array containing the sorted elements. So far, I know how to implement a regular merge sort. How would I modify this code so that it implements a K-way merge sort? (Note: this function doesn't return the sorted array, I need help with that as well. It also doesn't take in K, since its a regular merge sort)
Below code:
public class MergeSort {
public static void main(String[] args) {
}
public static void mergeSort(int[] inputArray) {
int size = inputArray.length;
if (size < 2)
return;
int mid = size / 2;
int leftSize = mid;
int rightSize = size - mid;
int[] left = new int[leftSize];
int[] right = new int[rightSize];
for (int i = 0; i < mid; i++) {
left[i] = inputArray[i];
}
for (int i = mid; i < size; i++) {
right[i - mid] = inputArray[i];
}
mergeSort(left);
mergeSort(right);
merge(left, right, inputArray);
}
public static void merge(int[] left, int[] right, int[] arr) {
int leftSize = left.length;
int rightSize = right.length;
int i = 0, j = 0, k = 0;
while (i < leftSize && j < rightSize) {
if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
k++;
} else {
arr[k] = right[j];
k++;
j++;
}
}
while (i < leftSize) {
arr[k] = left[i];
k++;
i++;
}
while (j < leftSize) {
arr[k] = right[j];
k++;
j++;
}
}
}
Regular merge sort is two-way sorting. You compare elements from the first and the second halves of array and copy smallest to output array.
For k-way sorting you divide input array into K parts. K indexes point to the first elements of every part. To effectively choose the smallest of them, use priority queue (based on binary heap) and pop the smallest element from the heap top at every step. When you pop element belonging to the m-th part, push the next element from the same part (if it still exists)
Let you have array length 16 and k = 4.
The first recursion level calls 4 mergesorts for arrays copied from indexes 0..3, 4..7, 8..11, 12..15.
The second recursion level gets length 4 array and calls 4 mergesorts for 1-element arrays.
The third recursion level gets length 1 array and immediately returns (such array is sorted).
Now at the second recursion level you merge 4 one-element arrays into one sorted array.
Now at the first recursion level you merge 4 four-element arrays into one sorted array length 16

Making 2 Modifications to a Bubblesort Program

I have to make the following 2 modifications to a simple bubblesort program:
After the first pass, the largest number is guaranteed to be in the highest-numbered element of the array; after the second pass, the two highest numbers are “in place”; and so on. Instead of making nine comparisons on every pass, modify the bubble sort to make eight comparisons on the second pass, seven on the third, and so on.
The data in the array may already be in the proper order or near proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass if any swaps have been made. If none have been made, the data must already be in the proper order, so the program should terminate. If swaps have been made, at least one more pass is needed."
Any help as to how I should approach these would be greatly appreciated!
//sort elements of array with bubble sort
public static void bubbleSort (int array2[])
{
//loop to control number of passes
for (int pass = 1; pass < array2.length; pass++)
{
//loop to control number of comparisons
for (int element = 0; element < array2.length - 1; element++)
{
//compare side-by-side elements and swap them if
//first element is greater than second element
if (array2[element] > array2[element + 1]){
swap (array2, element, element + 1);
}
}
}
}
//swap two elements of an array
public static void swap (int array3[], int first, int second)
{
//temporary holding area for swap
int hold;
hold = array3[first];
array3[first] = array3[second];
array3[second] = hold;
}
I think this will do for you. A boolean is added to check and the run (j) is subtracted from the input.length for each run.
public static int[] bubbleSort(int input[])
{
int i, j, tmp;
bool changed;
for (j = 0; j < input.length; j++)
{
changed = false;
for (i = 1; i < input.length - j; i++)
{
if (tmp[i-1] > input[i])
{
tmp= input[i];
input[i] = input[i-1];
input[i-1] = tmp;
changed = true;
}
}
if (!changed) return input;
}
return input;
}

Sorting arrays (Bubble Sort)

I have a small doubt while sorting arrays and yeah I am new to programming. Take a look at this code for example:
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
In the above code, why do we have to use j++ and i < (array.length-j) as the test expression? We could have rather used i < (array.length) as the test expression while omitting the variable j. Any answers?
"Why do we have to use j++ and i < (array.length-j) as the test expression?"
The reason behind is at any time elements array[ array.length -j ] to array[array.length - 1] are already sorted.
Example: Say you have array of length n.
So after the first iteration the biggest element will be placed at array[n - 1].
So because the largest element is already sorted on the next iteration we will only sort array of length n - 1.
After the second iteration the second biggest element will be placed at array[ n - 2].
So because the 1st largest and 2nd largest elements are already sorted on the next iteration we will only sort array of length n - 2, and so on...
The running time of the algorithm will be which is
As you said it we could have used i < (array.length - 1) but we will be just doing a lot of work for nothing. If we do this the running time will be (nn) which is O(nn). But though the running time is still O(n*n) but it is obvious that is smaller than , hence the first one is efficient.

Are the following two recursive sorting methods the same?

I've been working on selection sort and bubble sort using recursion. I've finally come up with two methods, and they worked perfectly fine. But as I took a final look at those, they look like just one one method which is selectionSortRecursive. Could you tell me the difference (or are they the same)?
public static void selectionSortRecursive(Comparable[] list, int n)
{
Comparable temp;
if ( n > 1 ){
for ( int i = 0; i < n - 1; i++ )
{
if(list[i].compareTo(list[i + 1]) > 0){
temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
}
}
selectionSortRecursive(list, n - 1);
}
}
public static void bubbleSortRecursive( Comparable[] list, int n)
{
Comparable tmp;
if (n >1) {
for (int i = 0; i < n - 1; i++)
{
if(list[i+1].compareTo(list[i]) < 0)
{
tmp = list[i];
list[i] = list[i+1];
list[i+1] = tmp;
}
}
bubbleSortRecursive( list, n - 1);
}
}
The only line which is different is
if(list[i].compareTo(list[i + 1]) > 0){
and
if(list[i+1].compareTo(list[i]) < 0)
and provided compareTo is implemented correctly this will do the same thing.
BTW the if(n > 1) check is redundant. And I would move tmp to the most inner scope you can.
Both sorts are bubble sorts. A bubble sort "bubbles" values to the top/right position.
A selection sort selects the lowest/highest value repeatedly, swap in the selected with the position it needs to place it. i.e. the swap would be outside the loop to find the lowest/highest.
It's both bubble sort, one bubbles the element from the top to the bottom, the other one does it the way round. Selection sort is different: it searches the smallest elements of all remaining (unsorted) elements and places it in the next slot, it does not change any other elements. Bubble sort, instead, always compares tow elements and swaps them is the first one is bigger (or smaller) than the second one - which is what you are doing.

Categories

Resources