• + 0 comments

    Java

            // Write your code here
            AtomicInteger count = new AtomicInteger();
            AtomicInteger totalCount = new AtomicInteger();
            count.set(0);
            totalCount.set(0);
            do {
                count.set(0);
                IntStream.range(0, a.size()-1).forEach(x -> {
                    if (a.get(x) > a.get(x + 1)) {
                        Collections.swap(a, x, x + 1);
                        totalCount.incrementAndGet();
                        count.incrementAndGet();
    
                    }
                });
            } while (count.get() > 0);
            System.out.println(String.format("Array is sorted in %s swaps.", totalCount));
            System.out.println(String.format("First Element: %s", a.get(0)));
            System.out.println(String.format("Last Element: %s", a.get(a.size()-1)));
        }