Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

พิมพ์ n ตัวเลขที่น้อยที่สุดจากอาร์เรย์ในลำดับเดิม

ได้รับอาร์เรย์ k ตัว ต้องหา n ตัวเลขที่น้อยที่สุดในลำดับที่ปรากฏ

Input: arr[] = {1, 2, 4, 3, 6, 7, 8}, k=3
Output: 1, 2, 3

อัลกอริทึม

START
Step 1 -> start variables as int i, max, pos, j, k=4 and size for array size
Step 2 -> Loop For i=k and i=0 and j--
        If arr[j] > max
            Set max = arr[j]
            Set pos = j
        End
    End
    IF max > arr[i]
        Set j = pos
        Loop While j < k-1
            Set arr[j] = arr[j+1]
            Set j++
        End
        Set arr[k-1] = arr[i]
    End IF
End
Step 3 -> Loop For i = 0 and i < k and i++
    Print arr[i]
STOP

ตัวอย่างโค้ด (C)

#include <stdio.h>

int main() {
    int arr[] = {5, 8, 3, 1, 2, 9};
    int i, max, pos, j, k = 4;
    int size = sizeof(arr)/sizeof(arr[0]);
    for (i = k; i < size; i++) {
        max = arr[k-1];
        pos = k-1;
        for (j = k-2; j >= 0; j--) {
            if (arr[j] > max) {
                max = arr[j];
                pos = j;
            }
        }
        if (max > arr[i]) {
            j = pos;
            while (j < k-1) {
                arr[j] = arr[j+1];
                j++;
            }
            arr[k-1] = arr[i];
        }
    }
    for (i = 0; i < k; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

ผลลัพธ์

5 3 1 2