int uArray[15] = {12, 9, 5, 2, 7, 1, 6, 8, 1, 14, 11, 13, 9, 4, 15}; // Unsorted array
int sArray[15]; // Sorted array
int indexArray[15]; // Index array
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Sort the unsorted array and keep track of the changes
sortArray(uArray, sArray, indexArray, 15);
// Print the sorted array and the index array
Serial.println("Sorted array:");
for (int i = 0; i < 15; i++) {
Serial.print(sArray[i]);
Serial.print(", ");
}
Serial.println("");
Serial.println("Index array:");
for (int i = 0; i < 15; i++) {
Serial.print(indexArray[i]);
Serial.print(", ");
}
Serial.println("");
// Test the findPosition() function
int index = findPosition(sArray[9], sArray, indexArray, 15);
Serial.print("Index of ");
Serial.print(sArray[9]);
Serial.print(" in the original array: ");
Serial.println(index);
Serial.print("sArray[9]= ");
Serial.print(sArray[9]);
Serial.print(" uArray[");
Serial.print(index);
Serial.print("]= ");
Serial.println(uArray[index]);
}
void loop() {
// Do nothing
}
void sortArray(int* uArray, int* sArray, int* indexArray, int length) {
// Copy the unsorted array to the sorted array and index array
for (int i = 0; i < length; i++) {
sArray[i] = uArray[i];
indexArray[i] = i;
}
// Sort the sorted array using bubble sort algorithm
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - i - 1; j++) {
if (sArray[j] > sArray[j+1]) {
// Swap the elements in the sorted array
int temp = sArray[j];
sArray[j] = sArray[j+1];
sArray[j+1] = temp;
// Swap the elements in the index array
temp = indexArray[j];
indexArray[j] = indexArray[j+1];
indexArray[j+1] = temp;
}
}
}
}
int findPosition(int value, int* sArray, int* indexArray, int length) {
// Search for the value in the sorted array
for (int i = 0; i < length; i++) {
if (sArray[i] == value) {
// Return the index of the value in the original array
return indexArray[i];
}
}
// Return -1 if the value is not found in the sorted array
return -1;
}