Search Your Question

Write program for ascending sorting Int Array in any language

Ans : 
(Interviewer told syntax doesn't matter, write pseudo-code type program)

1. Not using direct function.

 void main()
    {

        int i, j, a, n, number[30];
        printf("Enter the value of N \n");
        scanf("%d", &n);

        printf("Enter the numbers \n");
        for (i = 0; i < n; ++i)
            scanf("%d", &number[i]);

        for (i = 0; i < n; ++i)
        {

            for (j = i + 1; j < n; ++j)
            {

                if (number[i] > number[j])
                {

                    a =  number[i];
                    number[i] = number[j];
                    number[j] = a;

                }

            }

        }

        printf("The numbers arranged in ascending order are given below \n");
        for (i = 0; i < n; ++i)
            printf("%d\n", number[i]);

    }

2. If we write in swift using higher order function, then

var numbers = [45,6,113,56,8,56,43,78]

print(numbers.sort()) //Sorting in Ascending order

print(numbers.sort(>)) //Sorting in Descending order

Interviewer mostly asked this question to check your programming logic. So he/she don't require syntax.

Q. Sorting strings array
A.
Method 1 : 
var sortedArray = swiftArray.sorted { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedAscending }

Method 2 : 
let sortedNames = names.sort { $0.name < $1.name }
let sortedNames = names.sorted(by: <)


No comments:

Post a Comment

Thanks