How can I remove duplicate elements from a given array in java without using collections

后端 未结 10 765
逝去的感伤
逝去的感伤 2021-01-06 02:20

I have an array elements like this:

int arr[] = {1,1,2,2,3,3,4,4};

I want to remove the duplicate elements from. Searched on the internet

10条回答
  •  醉梦人生
    2021-01-06 03:13

    Got a very Good Solution for this question : and it works perfectly . For those who are still searching answer for this question , you can use this below piece of code.

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    public class DuplicatesRemove {
    
    public static void main(String[] args) throws Exception {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    
        System.out.print("Enter the array size :");
        int size = Integer.parseInt(br.readLine());
    
        int[] arr = new int[size];
    
        // Creating the array
        for (int i = 0; i < size; i++) {
            System.out.print("Enter the element arr[" + i + "] = ");
            arr[i] = Integer.parseInt(br.readLine());
            System.out.println();
        }
    
        // displaying the array - it may contain elements in unsorted manner
        System.out.println("Before Sorting :");
        for (int i = 0; i < size; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
        }
        System.out
                .println("*****************************************************");
    
        // Logic for sorting the elements in the array
        for (int i = 0; i < size; i++) {
            for (int j = 1; j < size - i; j++) {
                if (arr[j - 1] > arr[j]) {
                    int temp = arr[j];
                    arr[j] = arr[j - 1];
                    arr[j - 1] = temp;
                }
            }
        }
    
        // Printing the sorted elements - it may contain duplicate elements
        System.out.println("After Sorting :");
        for (int i = 0; i < size; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
        }
    
        System.out
                .println("*****************************************************");
        // Logic for removing the duplicate elements
        int compare = 0;
        arr[compare] = arr[0];
    
        for (int i = 1; i < size; i++) {
            if (arr[compare] != arr[i]) {
                compare++;
                arr[compare] = arr[i];
            }
        }
    
        System.out.println("Array After removing duplicate elements is :");
        for (int i = 0; i <= compare; i++) {
            System.out.println("Element arr[" + i + "] = " + arr[i]);
          }
       }
    }
    

提交回复
热议问题