703433. Sort the pile of cards

Easy

Sort the Pile of Cards

Slug: sort-the-pile-of-cards3733

Difficulty: Easy

Id: 703433

Topic Tags: Arrays, Data Structures

Company Tags: BankBazaar

Summary

The problem is about sorting a pile of cards in a specific order. The key concept involved is arrays and data structures. Given a list of numbers representing the cards in a pile, you need to sort them in ascending order.

Detailed Explanation

To solve this problem, we can use a simple array-based algorithm like Bubble Sort or Quick Sort. Here's a step-by-step breakdown of the solution using Bubble Sort:

  • Initialize an array cards with the given numbers.
  • Define a function bubbleSort that takes the cards array as input and returns the sorted array.
  • In the bubbleSort function:
    • Iterate through the cards array until no more swaps are needed (i.e., the array is sorted).
    • For each iteration, iterate through the array from the first element to the second-to-last element.
    • Compare adjacent elements and swap them if they're in the wrong order.
  • Return the sorted cards array.

Here's an example of what the algorithm would look like for a sample input:

Input: [5, 2, 8, 3, 1, 6, 4]
Output: [1, 2, 3, 4, 5, 6, 8]

The time complexity of Bubble Sort is O(n^2), where n is the length of the input array. The space complexity is O(1) since we only use a small amount of extra memory to store the sorted array.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] sortCards(int[] cards) {
    for (int i = 0; i < cards.length - 1; i++) {
        for (int j = 0; j < cards.length - i - 1; j++) {
            if (cards[j] > cards[j + 1]) {
                int temp = cards[j];
                cards[j] = cards[j + 1];
                cards[j + 1] = temp;
            }
        }
    }
    return cards;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.