Sponsored
Sponsored
This approach involves iterating through the list and swapping every two consecutive students. The loop runs with a step of 2 to handle even-indexed pairs, ensuring that swaps are done pair-wise. If the total number of students is odd, the last student remains in their original position as there is no pair to swap with.
Time Complexity: O(n), since each element may be swapped once.
Space Complexity: O(1), as no extra space is used except the temporary variable for swapping.
1#include <stdio.h>
2
3void swapSeats(char students[][20], int n) {
4 for (int i = 0; i < n - 1; i += 2) {
5 char temp[20];
6 strcpy(temp, students[i]);
7 strcpy(students[i], students[i + 1]);
8 strcpy(students[i + 1], temp);
9 }
10}
11
12int main() {
13 char students[][20] = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
14 int n = 5;
15
16 swapSeats(students, n);
17
18 for (int i = 0; i < n; i++) {
19 printf("%d %s\n", i + 1, students[i]);
20 }
21 return 0;
22}
The C code uses an array of strings to represent students. It swaps the seats by iterating through the array with a step of 2. For each iteration, it swaps the student names using a temporary variable. The last student remains unaltered if the number of students is odd since the iteration breaks before reaching them.
This method employs a temporary array or list to store swapped results before copying them back to the original list or directly returning them as new results. This makes the logic conceptually simpler at the cost of some additional space usage.
Time Complexity: O(n) due to linear traversal.
Space Complexity: O(n), using a full-sized temporary array.
1#include
The C variant uses an extra 2D array to initially store swapped pairs, maintaining the original array intact. It later prints the new results by referencing the temporary storage after all swaps are completed.