I have made the following program and implemented the merge sort where it sorts an array that the user fills and then picks any duplicate values from the array. However, I have a small problem in the main method. Example: I input the number 4 three times and it would display "duplicate: 4" two times; my goal here is to let it display only once, irrelevant of how many duplicates of 4 there are. Thanks guys.
import java.util.*;
`public class Question6` {
static void mergeSort(int arr1[], int o, int k, int x) {
int num1 = k - o + 1;
int num2 = x - k;
int temp1[] = new int [num1]; //creation of two temporary arrays to store in
int temp2[] = new int [num2];
for (int i=0; i<num1; ++i) //for loops to copy the data to the temporary arrays
temp1[i] = arr1[o + i];
for (int j=0; j<num2; ++j)
temp2[j] = arr1[k + o + j];
int i = 0, j = 0; //starting position of temporary arrays
int s = l; //starting position of the merged two temporary arrays
while (i < num1 && j < num2) {
if (temp1[i] <= temp2[j]) {
arr1[s] = temp1[i];
i++;
}
else {
arr1[s] = temp2[j];
j++;
}
s++;
}
//code to copy elements from temp1
while (i < num1)
{
arr1[s] = temp1[i];
i++;
s++;
}
//code to copy elements from temp2
while (j < num2)
{
arr1[s] = temp2[j];
j++;
s++;
}
}
/
void forSorting(int arr2[], int o, int x) //main method that carries out merge sort
{
if (o < x)
{
// Find the middle point
int a = (o+x)/2;
// Sort first and second halves
forSorting(arr2, o, a);
forSorting(arr2, a+1, x);
// Merge the sorted halves
mergeSort(arr2, o, a, x);
}
}
public static void main(String[] args) {
Question6 qs = new Question6();
Scanner sc = new Scanner(System.in);
int [] duplicate = new int[10];
System.out.println("Please input the numbers to be checked for repetition.");
for(int x = 0; x < 10; x++)
{
duplicate[x] = sc.nextInt(); //filling array
}
int length = duplicate.length;
qs.forSorting(duplicate, 0, length-1); //calling method forSorting
System.out.println(Arrays.toString(duplicate)); //displays array
for (int count = 1; count < 10; count++)
{
if (duplicate[count] == duplicate[count - 1]) {
//displays the duplicates
System.out.println("Duplicate: " + duplicate[count]);
}
}
}
}